package game

import (
	"fmt"
	"server/GoUtil"
	"server/MergeConst"
	"server/cron"
	"server/db"
	"server/gamedata"
	"server/msg"
	"strconv"
	"strings"
	"time"

	"google.golang.org/protobuf/proto"
)

type PlayerActiveData struct {
	*PlayerData

	WeekCronID cron.EntryID
	Mcron      *cron.Cron
	Type       int32
	MisDirty   bool
	MActType   int
	MActiveID  int32
}

func (p *PlayerActiveData) DeleteOutlineActive(deleteList []int32, tableName string) {
	sqlStr := "DELETE FROM " + tableName + " WHERE ActiveID = ?"
	for i := 0; i < len(deleteList); i++ {

		result, err := db.SqlDb.Exec(sqlStr, deleteList[i])
		if err != nil {
			fmt.Printf("exec failed, err:%v\n", err)
			return
		}
		affectedRows, err := result.RowsAffected()
		if err != nil {
			fmt.Printf("get affected failed, err:%v\n", err)
			return
		}
		fmt.Printf("delete data success, affected rows:%d\n", affectedRows)
	}
}

func (p *PlayerActiveData) OpenNewLimitActivity(args []interface{}) {
	if p.MActType != args[3].(int) {
		return
	}
	p.MisDirty = true
}

func (p *PlayerActiveData) ClearData() bool {
	GoUtil.RemoveEvent(MergeConst.OpenNewLimitActivity, p.OpenNewLimitActivity, p)
	return true
}
func (p *PlayerActiveData) Reconnect(b bool) {
	GoUtil.RemoveEvent(MergeConst.OpenNewLimitActivity, p.OpenNewLimitActivity, p)
	GoUtil.RegisterEvent(MergeConst.OpenNewLimitActivity, p.OpenNewLimitActivity, p)

}

// ////////////////////////
type PlayerPassportData struct {
	*PlayerActiveData
	Data       msg.ResLimitPassportDetail
	MsqlStruck []db.SqlLimitPassportStruct
	MActType   int
}

func (p *PlayerPassportData) LoadDataFromDB(dwUin interface{}) bool {

	sqlStr := "SELECT * FROM t_player_LimitPassport WHERE dwUin = ?"
	p.MsqlStruck = []db.SqlLimitPassportStruct{}

	if err := db.SqlDb.Select(&p.MsqlStruck, sqlStr, dwUin.(int32)); err != nil {
		fmt.Printf("get data failed, err:%v\n", err)
		p.IsHaveDataDb = false
	} else {
		p.IsHaveDataDb = true
	}

	p.Data.DwUin = dwUin.(int32)
	deleteList := []int{}
	dlist := []int32{}
	tempList := []db.SqlLimitPassportStruct{}
	curtime := time.Now().Unix()
	startIndex := 0
	for i := 0; i < len(p.MsqlStruck); i++ {
		item := p.MsqlStruck[i]
		if item.StartSvrTime > int32(curtime) || item.EndSvrTime < int32(curtime) {
			deleteList = append(deleteList, i)
		}
	}
	for i := 0; i < len(deleteList); i++ {
		curIndex := deleteList[i]
		if curIndex == startIndex {
			startIndex = startIndex + 1
			continue
		}
		tempList = append(tempList, p.MsqlStruck[startIndex:curIndex]...)
		startIndex = curIndex + 1
	}
	if startIndex <= len(p.MsqlStruck)-1 {
		tempList = append(tempList, p.MsqlStruck[startIndex:]...)
	}
	for i := 0; i < len(deleteList); i++ {
		dlist = append(dlist, p.MsqlStruck[deleteList[i]].ActiveID)
	}
	if len(dlist) > 0 {
		p.DeleteOutlineActive(dlist, "t_player_LimitPassport")
	}
	p.MsqlStruck = tempList
	p.MActType = 1
	p.Reconnect(false)
	return true
}

func (p *PlayerPassportData) CloseNewLimitActivity(args []interface{}) {
	record := args[0].(*gamedata.ActivityRecord)

	if record.Type != p.MActType {
		return
	}

	notify := &msg.NotifyLimitedTimeActiveEnd{}
	notify.DwUin = p.M_Player.M_DwUin
	notify.MActiveList = []*msg.LimitedTimeEndStruct{}

	for i := 0; i < len(p.MsqlStruck); i++ {
		item := p.MsqlStruck[i]
		if int(item.ConfigActId) == record.Id {
			msg := &msg.LimitedTimeEndStruct{}
			msg.ActiveID = item.ActiveID
			msg.Type = int32(record.Type)
			notify.MActiveList = append(notify.MActiveList, msg)
		}
	}
	p.MisDirty = true
	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(notify)
	G_getGameLogic().PackResInfo(agent, "NotifyLimitedTimeActiveEnd", data)
}

func (p *PlayerPassportData) Reconnect(b bool) {
	GoUtil.RemoveEvent(MergeConst.CloseNewLimitActivity, p.CloseNewLimitActivity, p)
	GoUtil.RegisterEvent(MergeConst.CloseNewLimitActivity, p.CloseNewLimitActivity, p)
	p.PlayerActiveData.Reconnect(b)
}

func (p *PlayerPassportData) FindDbSt(activeId int32) *db.SqlLimitPassportStruct {
	for i := 0; i < len(p.MsqlStruck); i++ {
		if p.MsqlStruck[i].ActiveID == activeId {
			return &p.MsqlStruck[i]
		}
	}
	return nil
}

func (p *PlayerPassportData) ResLimitPassportDetail(buf []byte) {
	req := &msg.ReqLimitPassportDetail{}
	proto.Unmarshal(buf, req)
	st := p.FindDbSt(req.ActiveID)
	res := &msg.ResLimitPassportDetail{}
	if st != nil {

		res.ActiveID = st.ActiveID
		res.CurFreeLv = st.CurFreeLv
		res.CurPayLv = st.CurPayLv
		res.CurSvrTime = int32(time.Now().Unix())
		res.StartSvrTime = st.StartSvrTime
		res.EndSvrTime = st.EndSvrTime
		res.IsPay = st.IsPay
		res.DwUin = p.M_Player.M_DwUin
		res.Star = st.Star
		res.Status = st.Status
		res.ResultCode = 0

	} else {
		res.ResultCode = MergeConst.Protocol_Active_No_Exsit
	}
	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(res)
	G_getGameLogic().PackResInfo(agent, "ResLimitPassportDetail", data)
}

func (p *PlayerPassportData) ResGetLimitPassportReward(buf []byte) {
	req := &msg.ReqGetLimitPassportReward{}
	proto.Unmarshal(buf, req)
	st := p.FindDbSt(req.ActiveID)
	res := &msg.ResGetLimitPassportReward{}
	if st != nil {
		res.ActiveID = st.ActiveID
		res.DwUin = p.M_Player.M_DwUin
		res.FreeOrPay = req.FreeOrPay
		res.ReqLv = req.ReqLv
		res.ResultCode = 0
		if req.FreeOrPay == 1 {
			st.CurFreeLv = req.ReqLv
		}
		if req.FreeOrPay == 2 {
			st.CurPayLv = req.ReqLv
		}
	} else {
		res.ResultCode = MergeConst.Protocol_Active_No_Exsit
	}
	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(res)
	G_getGameLogic().PackResInfo(agent, "ResGetLimitPassportReward", data)
}

func (p *PlayerPassportData) ResPayPassport(buf []byte) {
	req := &msg.ReqPayPassport{}
	proto.Unmarshal(buf, req)
	st := p.FindDbSt(req.ActiveID)
	res := &msg.ResPayPassport{}
	if st != nil {
		res.DwUin = p.M_Player.M_DwUin
		st.IsPay = 1
		res.ResultCode = 0
		res.ActiveID = req.ActiveID
	} else {
		res.ResultCode = MergeConst.Protocol_Active_No_Exsit
	}
	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(res)
	G_getGameLogic().PackResInfo(agent, "ResPayPassport", data)
}

func (p *PlayerPassportData) ResActiveAddStar(buf []byte) {
	req := &msg.ReqActiveAddStar{}
	proto.Unmarshal(buf, req)
	st := p.FindDbSt(req.ActiveID)
	res := &msg.ResActiveAddStar{}
	if st != nil {
		st.Star = req.AddCnt + st.Star
		res.AllCnt = st.Star
		res.ActiveID = req.ActiveID
	} else {
		res.ResultCode = MergeConst.Protocol_Active_No_Exsit
	}
	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(res)
	G_getGameLogic().PackResInfo(agent, "ResActiveAddStar", data)
}

func (p *PlayerPassportData) SaveDataFromDB(Key interface{}) bool {
	for i := 0; i < len(p.MsqlStruck); i++ {
		item := p.MsqlStruck[i]
		db.FormatAllMemUpdateDb(&item, "t_player_LimitPassport", "ActiveID")
	}
	return true
}
func (p *PlayerPassportData) ClearData() bool {
	p.SaveDataFromDB("")
	GoUtil.RemoveEvent(MergeConst.CloseNewLimitActivity, p.CloseNewLimitActivity, p)
	p.PlayerActiveData.ClearData()

	return true
}

////////////////////////

type PlayerPromotionData struct {
	*PlayerActiveData
	Data       msg.ResLimitPassportDetail
	MsqlStruck []db.SqlLimitPromotionStruct
	MActType   int
}

func (p *PlayerPromotionData) LoadDataFromDB(dwUin interface{}) bool {

	sqlStr := "SELECT * FROM t_player_LimitPromotion WHERE dwUin = ?"
	p.MsqlStruck = []db.SqlLimitPromotionStruct{}

	if err := db.SqlDb.Select(&p.MsqlStruck, sqlStr, dwUin.(int32)); err != nil {
		fmt.Printf("get data failed, err:%v\n", err)
		p.IsHaveDataDb = false
	} else {
		p.IsHaveDataDb = true
	}

	p.Data.DwUin = dwUin.(int32)
	deleteList := []int{}
	dlist := []int32{}
	tempList := []db.SqlLimitPromotionStruct{}
	curtime := time.Now().Unix()
	startIndex := 0
	for i := 0; i < len(p.MsqlStruck); i++ {
		item := p.MsqlStruck[i]
		if item.StartSvrTime > int32(curtime) || item.EndSvrTime < int32(curtime) {
			deleteList = append(deleteList, i)
		}
	}
	for i := 0; i < len(deleteList); i++ {
		curIndex := deleteList[i]
		if curIndex == startIndex {
			startIndex = startIndex + 1
			continue
		}
		tempList = append(tempList, p.MsqlStruck[startIndex:curIndex]...)
		startIndex = curIndex + 1
	}
	if startIndex <= len(p.MsqlStruck)-1 {
		tempList = append(tempList, p.MsqlStruck[startIndex:]...)
	}
	for i := 0; i < len(deleteList); i++ {
		dlist = append(dlist, p.MsqlStruck[deleteList[i]].ActiveID)
	}
	if len(dlist) > 0 {
		p.DeleteOutlineActive(dlist, "t_player_LimitPromotion")
	}
	p.MActType = 2
	p.MsqlStruck = tempList
	p.Reconnect(false)
	return true
}

func (p *PlayerPromotionData) CloseNewLimitActivity(args []interface{}) {
	record := args[0].(*gamedata.ActivityRecord)

	if record.Type != p.MActType {
		return
	}

	notify := &msg.NotifyLimitedTimeActiveEnd{}
	notify.DwUin = p.M_Player.M_DwUin
	notify.MActiveList = []*msg.LimitedTimeEndStruct{}

	for i := 0; i < len(p.MsqlStruck); i++ {
		item := p.MsqlStruck[i]
		if int(item.ConfigActId) == record.Id {
			msg := &msg.LimitedTimeEndStruct{}
			msg.ActiveID = item.ActiveID
			msg.Type = int32(record.Type)
			notify.MActiveList = append(notify.MActiveList, msg)
		}
	}
	p.MisDirty = true
	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(notify)
	G_getGameLogic().PackResInfo(agent, "NotifyLimitedTimeActiveEnd", data)
}

func (p *PlayerPromotionData) Reconnect(b bool) {
	GoUtil.RemoveEvent(MergeConst.CloseNewLimitActivity, p.CloseNewLimitActivity, p)
	GoUtil.RegisterEvent(MergeConst.CloseNewLimitActivity, p.CloseNewLimitActivity, p)
	p.PlayerActiveData.Reconnect(b)
}

func (p *PlayerPromotionData) FindDbSt(activeId int32) *db.SqlLimitPromotionStruct {
	for i := 0; i < len(p.MsqlStruck); i++ {
		if p.MsqlStruck[i].ActiveID == activeId {
			return &p.MsqlStruck[i]
		}
	}
	return nil
}

func (p *PlayerPromotionData) ResPromotionDetail(buf []byte) {
	req := &msg.ReqPromotionDetail{}
	proto.Unmarshal(buf, req)
	st := p.FindDbSt(req.ActiveID)
	res := &msg.ResPromotionDetail{}
	if st != nil {
		res.ActiveID = st.ActiveID
		res.CurSvrTime = int32(time.Now().Unix())
		res.StartSvrTime = st.StartSvrTime
		res.EndSvrTime = st.EndSvrTime
		res.IsPay = st.IsPay
		res.DwUin = p.M_Player.M_DwUin
		res.ResultCode = 0
	} else {
		res.ResultCode = MergeConst.Protocol_Active_No_Exsit
	}
	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(res)
	G_getGameLogic().PackResInfo(agent, "ResPromotionDetail", data)
}

func (p *PlayerPromotionData) ResBuyLimitPromotionReward(buf []byte) {
	req := &msg.ReqBuyLimitPromotionReward{}
	proto.Unmarshal(buf, req)
	st := p.FindDbSt(req.ActiveID)
	res := &msg.ResBuyLimitPromotionReward{}
	if st != nil {
		res.ActiveID = st.ActiveID
		res.DwUin = p.M_Player.M_DwUin
		st.IsPay = 1
		res.ResultCode = 0
	} else {
		res.ResultCode = MergeConst.Protocol_Active_No_Exsit
	}
	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(res)
	G_getGameLogic().PackResInfo(agent, "ResBuyLimitPromotionReward", data)
}

func (p *PlayerPromotionData) ClearData() bool {
	p.SaveDataFromDB("")
	GoUtil.RemoveEvent(MergeConst.CloseNewLimitActivity, p.CloseNewLimitActivity, p)
	p.PlayerActiveData.ClearData()
	return true
}

func (p *PlayerPromotionData) SaveDataFromDB(Key interface{}) bool {
	for i := 0; i < len(p.MsqlStruck); i++ {
		item := p.MsqlStruck[i]
		db.FormatAllMemUpdateDb(&item, "t_player_LimitPromotion", "ActiveID")
	}
	return true
}

////////////////////////

////////////////////////

type Player7DayLoginData struct {
	*PlayerActiveData
	Data       msg.ResLimitPassportDetail
	MsqlStruck []db.SqlSevenDayLoginStruct
}

func (p *Player7DayLoginData) LoadDataFromDB(dwUin interface{}) bool {

	sqlStr := "SELECT * FROM t_player_Limit7DayLogin WHERE dwUin = ?"
	p.MsqlStruck = []db.SqlSevenDayLoginStruct{}

	if err := db.SqlDb.Select(&p.MsqlStruck, sqlStr, dwUin.(int32)); err != nil {
		fmt.Printf("get data failed, err:%v\n", err)
		p.IsHaveDataDb = false
	} else {
		p.IsHaveDataDb = true
	}

	p.Data.DwUin = dwUin.(int32)
	deleteList := []int{}
	dlist := []int32{}
	tempList := []db.SqlSevenDayLoginStruct{}
	curtime := time.Now().Unix()
	startIndex := 0
	for i := 0; i < len(p.MsqlStruck); i++ {
		item := p.MsqlStruck[i]
		if item.StartSvrTime > int32(curtime) || item.EndSvrTime < int32(curtime) {
			deleteList = append(deleteList, i)
		}
	}
	for i := 0; i < len(deleteList); i++ {
		curIndex := deleteList[i]
		if curIndex == startIndex {
			startIndex = startIndex + 1
			continue
		}
		tempList = append(tempList, p.MsqlStruck[startIndex:curIndex]...)
		startIndex = curIndex + 1
	}
	if startIndex <= len(p.MsqlStruck)-1 {
		tempList = append(tempList, p.MsqlStruck[startIndex:]...)
	}
	for i := 0; i < len(deleteList); i++ {
		dlist = append(dlist, p.MsqlStruck[deleteList[i]].ActiveID)
	}
	if len(dlist) > 0 {
		p.DeleteOutlineActive(dlist, "t_player_Limit7DayLogin")
	}

	p.MsqlStruck = tempList
	p.Reconnect(false)
	return true
}

func (p *Player7DayLoginData) CloseNewLimitActivity(args []interface{}) {
	record := args[0].(*gamedata.ActivityRecord)

	if record.Type != p.MActType {
		return
	}

	notify := &msg.NotifyLimitedTimeActiveEnd{}
	notify.DwUin = p.M_Player.M_DwUin
	notify.MActiveList = []*msg.LimitedTimeEndStruct{}

	for i := 0; i < len(p.MsqlStruck); i++ {
		item := p.MsqlStruck[i]
		if int(item.ConfigActId) == record.Id {
			msg := &msg.LimitedTimeEndStruct{}
			msg.ActiveID = item.ActiveID
			msg.Type = int32(record.Type)
			notify.MActiveList = append(notify.MActiveList, msg)
		}
	}
	p.MisDirty = true
	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(notify)
	G_getGameLogic().PackResInfo(agent, "NotifyLimitedTimeActiveEnd", data)

}

func (p *Player7DayLoginData) Reconnect(b bool) {
	GoUtil.RemoveEvent(MergeConst.CloseNewLimitActivity, p.CloseNewLimitActivity, p)
	GoUtil.RegisterEvent(MergeConst.CloseNewLimitActivity, p.CloseNewLimitActivity, p)
	GoUtil.RemoveEvent(MergeConst.Notify_Daily_Renew, p.NotifyDailyRenew7Day, p)
	GoUtil.RegisterEvent(MergeConst.Notify_Daily_Renew, p.NotifyDailyRenew7Day, p)

	p.PlayerActiveData.Reconnect(b)
}

func (p *Player7DayLoginData) NotifyDailyRenew7Day(param []interface{}) {
	// p.Data.RenewTime = int32(param[0].(int64))
	// for k := range p.Data.MEmitUnlockData {
	// 	p.Data.MEmitUnlockData[k] = 0
	// }

	p.NotifyDailyRenew7Dayfunc()
}

func (p *Player7DayLoginData) FindDbSt(activeId int32) *db.SqlSevenDayLoginStruct {
	for i := 0; i < len(p.MsqlStruck); i++ {
		if p.MsqlStruck[i].ActiveID == activeId {
			return &p.MsqlStruck[i]
		}
	}
	return nil
}

func (p *Player7DayLoginData) Res7DayLoginDetail(buf []byte) {
	req := &msg.Req7DayLoginDetail{}
	proto.Unmarshal(buf, req)
	st := p.FindDbSt(req.ActiveID)
	res := &msg.Res7DayLoginDetail{}
	if st != nil {
		res.ActiveID = st.ActiveID
		res.CurSvrTime = int32(time.Now().Unix())
		res.StartSvrTime = st.StartSvrTime
		res.EndSvrTime = st.EndSvrTime
		res.LastGetTime = st.LastGetTime
		res.DwUin = p.M_Player.M_DwUin

		res.GetIndex = st.GetIndex
		res.ResultCode = 0
	} else {
		res.ResultCode = MergeConst.Protocol_Active_No_Exsit
	}
	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(res)
	G_getGameLogic().PackResInfo(agent, "Res7DayLoginDetail", data)
}

func (p *Player7DayLoginData) ResGet7DayLoginPack(buf []byte) {
	req := &msg.ReqGet7DayLoginPack{}
	proto.Unmarshal(buf, req)
	st := p.FindDbSt(req.ActiveID)
	res := &msg.ResGet7DayLoginPack{}
	if st != nil {
		t := time.Unix((int64)(st.LastGetTime), 0).Local()
		nianchu1 := (int64)(st.LastGetTime) - (int64)(t.Hour()*3600+t.Minute()*60+t.Second())

		timeStamp := time.Now().Unix()
		t1 := time.Unix(timeStamp, 0).Local()
		nianchu2 := timeStamp - (int64)(t1.Hour()*3600+t1.Minute()*60+t1.Second())
		if nianchu1 == nianchu2 {
			res.ResultCode = MergeConst.Protocol_Active_7Day_Rewarded
		} else {
			res.ActiveID = st.ActiveID
			res.CurIndex = req.CurIndex + 1
			res.LastGetTime = int32(timeStamp)
			st.LastGetTime = res.LastGetTime
			st.GetIndex = req.CurIndex + 1

			res.DwUin = p.M_Player.M_DwUin
			res.ResultCode = 0
		}

	} else {
		res.ResultCode = MergeConst.Protocol_Active_No_Exsit
	}
	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(res)
	G_getGameLogic().PackResInfo(agent, "ResGet7DayLoginPack", data)
}

func (p *Player7DayLoginData) NotifyDailyRenew7Dayfunc() {
	notify := &msg.NotifyDailyRenew7Day{}

	notify.CurSvrTime = int32(time.Now().Unix())

	for i := 0; i < len(p.MsqlStruck); i++ {

		if (&p.MsqlStruck[i]).EndSvrTime > notify.CurSvrTime {
			agent := p.GetPlayer().GetAgentByPlayer()
			data, _ := proto.Marshal(notify)
			notify.ActiveID = (&p.MsqlStruck[i]).ActiveID
			G_getGameLogic().PackResInfo(agent, "NotifyDailyRenew7Day", data)
		}

	}

}

func (p *Player7DayLoginData) SaveDataFromDB(Key interface{}) bool {
	for i := 0; i < len(p.MsqlStruck); i++ {
		item := p.MsqlStruck[i]
		db.FormatAllMemUpdateDb(&item, "t_player_Limit7DayLogin", "ActiveID")
	}
	return true
}
func (p *Player7DayLoginData) ClearData() bool {
	p.SaveDataFromDB("")
	GoUtil.RemoveEvent(MergeConst.CloseNewLimitActivity, p.CloseNewLimitActivity, p)
	GoUtil.RemoveEvent(MergeConst.Notify_Daily_Renew, p.NotifyDailyRenew7Day, p)
	p.PlayerActiveData.ClearData()
	return true
}

////////////////////////

type PlayerInfinitePackData struct {
	*PlayerActiveData

	MsqlStruck []db.SqlLimitInfinitePackStruct
}

func (p *PlayerInfinitePackData) LoadDataFromDB(dwUin interface{}) bool {

	sqlStr := "SELECT * FROM t_player_LimitInfinitePack WHERE dwUin = ?"
	p.MsqlStruck = []db.SqlLimitInfinitePackStruct{}

	if err := db.SqlDb.Select(&p.MsqlStruck, sqlStr, dwUin.(int32)); err != nil {
		fmt.Printf("get data failed, err:%v\n", err)
		p.IsHaveDataDb = false
	} else {
		p.IsHaveDataDb = true
	}

	deleteList := []int{}
	dlist := []int32{}
	tempList := []db.SqlLimitInfinitePackStruct{}
	curtime := time.Now().Unix()
	startIndex := 0

	for i := 0; i < len(p.MsqlStruck); i++ {
		item := p.MsqlStruck[i]
		if item.StartSvrTime > int32(curtime) || item.EndSvrTime < int32(curtime) {
			deleteList = append(deleteList, i)
		}
	}
	for i := 0; i < len(deleteList); i++ {
		curIndex := deleteList[i]
		if curIndex == startIndex {
			startIndex = startIndex + 1
			continue
		}
		tempList = append(tempList, p.MsqlStruck[startIndex:curIndex]...)
		startIndex = curIndex + 1
	}
	if startIndex <= len(p.MsqlStruck)-1 {
		tempList = append(tempList, p.MsqlStruck[startIndex:]...)
	}
	for i := 0; i < len(deleteList); i++ {
		dlist = append(dlist, p.MsqlStruck[deleteList[i]].ActiveID)
	}
	if len(dlist) > 0 {
		p.DeleteOutlineActive(dlist, "t_player_LimitInfinitePack")
	}

	p.MsqlStruck = tempList
	p.Reconnect(false)
	return true
}

func (p *PlayerInfinitePackData) CloseNewLimitActivity(args []interface{}) {
	record := args[0].(*gamedata.ActivityRecord)

	if record.Type != p.MActType {
		return
	}

	notify := &msg.NotifyLimitedTimeActiveEnd{}
	notify.DwUin = p.M_Player.M_DwUin
	notify.MActiveList = []*msg.LimitedTimeEndStruct{}

	for i := 0; i < len(p.MsqlStruck); i++ {
		item := p.MsqlStruck[i]
		if int(item.ConfigActId) == record.Id {
			msg := &msg.LimitedTimeEndStruct{}
			msg.ActiveID = item.ActiveID
			msg.Type = int32(record.Type)
			notify.MActiveList = append(notify.MActiveList, msg)
		}
	}
	p.MisDirty = true
	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(notify)
	G_getGameLogic().PackResInfo(agent, "NotifyLimitedTimeActiveEnd", data)

}

func (p *PlayerInfinitePackData) Reconnect(b bool) {
	GoUtil.RemoveEvent(MergeConst.CloseNewLimitActivity, p.CloseNewLimitActivity, p)
	GoUtil.RegisterEvent(MergeConst.CloseNewLimitActivity, p.CloseNewLimitActivity, p)
	p.PlayerActiveData.Reconnect(b)
}

func (p *PlayerInfinitePackData) FindDbSt(activeId int32) *db.SqlLimitInfinitePackStruct {
	for i := 0; i < len(p.MsqlStruck); i++ {
		if p.MsqlStruck[i].ActiveID == activeId {
			return &p.MsqlStruck[i]
		}
	}
	return nil
}

func (p *PlayerInfinitePackData) ResInfinitePackDetail(buf []byte) {
	req := &msg.ReqInfinitePackDetail{}
	proto.Unmarshal(buf, req)
	st := p.FindDbSt(req.ActiveID)
	res := &msg.ResInfinitePackDetail{}
	if st != nil {
		res.ActiveID = st.ActiveID
		res.CurSvrTime = int32(time.Now().Unix())
		res.StartSvrTime = st.StartSvrTime
		res.EndSvrTime = st.EndSvrTime
		res.CurGear = st.CurGear
		res.DwUin = p.M_Player.M_DwUin
		res.ResultCode = 0
	} else {
		res.ResultCode = MergeConst.Protocol_Active_No_Exsit
	}
	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(res)
	G_getGameLogic().PackResInfo(agent, "ResInfinitePackDetail", data)
}

func (p *PlayerInfinitePackData) ResBuyInfinitePack(buf []byte) {
	req := &msg.ReqBuyInfinitePack{}
	proto.Unmarshal(buf, req)
	st := p.FindDbSt(req.ActiveID)
	res := &msg.ResBuyInfinitePack{}
	if st != nil {
		res.ActiveID = st.ActiveID
		res.DwUin = p.M_Player.M_DwUin
		res.ResultCode = 0
		st.CurGear = st.CurGear + 1
	} else {
		res.ResultCode = MergeConst.Protocol_Active_No_Exsit
	}
	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(res)
	G_getGameLogic().PackResInfo(agent, "ResBuyInfinitePack", data)
}

func (p *PlayerInfinitePackData) SaveDataFromDB(Key interface{}) bool {
	for i := 0; i < len(p.MsqlStruck); i++ {
		item := p.MsqlStruck[i]
		db.FormatAllMemUpdateDb(&item, "t_player_LimitInfinitePack", "ActiveID")
	}
	return true
}
func (p *PlayerInfinitePackData) ClearData() bool {
	p.SaveDataFromDB("")
	GoUtil.RemoveEvent(MergeConst.CloseNewLimitActivity, p.CloseNewLimitActivity, p)
	p.PlayerActiveData.ClearData()
	return true
}

// ////////////////////////
type PlayerCardCollectData struct {
	*PlayerActiveData
	// Data               msg.ResLimitPassportDetail
	MExchangeData      msg.ResExchangeCardBoxData
	MsqlStruck         []db.SqlCardCollectStruct
	MsqlExchangeStruck []db.SqlExchangeCardStruct
	MActType           int
}

func (p *PlayerCardCollectData) LoadDataFromDB(dwUin interface{}) bool {

	sqlStr := "SELECT * FROM t_player_card_data WHERE dwUin = ?"
	p.MsqlStruck = []db.SqlCardCollectStruct{}

	if err := db.SqlDb.Select(&p.MsqlStruck, sqlStr, dwUin.(int32)); err != nil {
		fmt.Printf("get data failed, err:%v\n", err)
		p.IsHaveDataDb = false
	} else {
		p.IsHaveDataDb = true
	}

	// p.Data.DwUin = dwUin.(int32)
	deleteList := []int{}
	dlist := []int32{}
	tempList := []db.SqlCardCollectStruct{}
	curtime := time.Now().Unix()
	startIndex := 0
	for i := 0; i < len(p.MsqlStruck); i++ {
		item := p.MsqlStruck[i]
		if item.StartSvrTime > int32(curtime) || item.EndSvrTime < int32(curtime) {
			deleteList = append(deleteList, i)
		}
	}
	for i := 0; i < len(deleteList); i++ {
		curIndex := deleteList[i]
		if curIndex == startIndex {
			startIndex = startIndex + 1
			continue
		}
		tempList = append(tempList, p.MsqlStruck[startIndex:curIndex]...)
		startIndex = curIndex + 1
	}
	if startIndex <= len(p.MsqlStruck)-1 {
		tempList = append(tempList, p.MsqlStruck[startIndex:]...)
	}
	for i := 0; i < len(deleteList); i++ {
		dlist = append(dlist, p.MsqlStruck[deleteList[i]].ActiveID)
	}
	if len(dlist) > 0 {
		p.DeleteOutlineActive(dlist, "t_player_card_data")
	}

	timeStamp := (int64)(time.Now().Unix())
	t := time.Unix(timeStamp, 0).Local()
	zero := timeStamp - (int64)(t.Hour()*3600+t.Minute()*60+t.Second())
	for i := 0; i < len(tempList); i++ {
		item := tempList[i]
		if item.RenewSvrTime < int32(zero) {
			tempList[i].RenewSvrTime = int32(zero)
			tempList[i].RenewExchangeTime = 0
			tempList[i].RenewRequestTime = 0
		}
	}
	p.MsqlStruck = tempList

	p.MActType = 5
	p.Reconnect(false)
	p.LoadExchangeCardData(dwUin.(int32))
	return true
}

func (p *PlayerCardCollectData) LoadExchangeCardData(dwUin int32) {
	sqlStr := "SELECT * FROM t_Player_ExchangeCard_Box_Data WHERE SenderId = ? OR ReceiveId = ?"
	p.MsqlExchangeStruck = []db.SqlExchangeCardStruct{}
	p.MExchangeData = msg.ResExchangeCardBoxData{}
	p.MExchangeData.ExchangeCardItems = []*msg.ExchangeCardItem{}
	if err := db.SqlDb.Select(&p.MsqlExchangeStruck, sqlStr, dwUin, dwUin); err != nil {

	} else {

	}

	deleteIDs := []int32{}
	for i := 0; i < len(p.MsqlExchangeStruck); i++ {
		item := p.MsqlExchangeStruck[i]
		ExchangeCard := &msg.ExchangeCardItem{}
		ExchangeCard.SenderId = item.SenderId
		ExchangeCard.ReceiveId = item.ReceiveId
		ExchangeCard.GroupId = item.GroupId
		ExchangeCard.ApplicateStatus = item.ApplicateStatus
		ExchangeCard.StartTime = item.StartTime
		ExchangeCard.EventType = item.EventType
		ExchangeCard.EventParam = item.EventParam
		ExchangeCard.ConfigActId = item.ConfigActId
		ExchangeCard.AutoId = item.AutoId
		if !p.IsInCardActivty(item.ConfigActId) {
			deleteIDs = append(deleteIDs, item.AutoId)
		} else {
			if ExchangeCard.EventType == 1 && ExchangeCard.ApplicateStatus == 2 && ExchangeCard.SenderId == dwUin {
				deleteIDs = append(deleteIDs, item.AutoId)
				continue
			}
			if ExchangeCard.EventType == 2 && ExchangeCard.ApplicateStatus == 4 && ExchangeCard.SenderId == dwUin {
				deleteIDs = append(deleteIDs, item.AutoId)
				continue
			}
			p.MExchangeData.ExchangeCardItems = append(p.MExchangeData.ExchangeCardItems, ExchangeCard)
		}

	}
	p.DeleteOutlineCardExchange(deleteIDs, "t_Player_ExchangeCard_Box_Data")
}

func (p *PlayerCardCollectData) ClearOutTimeline() {
	deleteIDs := []int32{}
	list := []*msg.ExchangeCardItem{}
	for i := 0; i < len(p.MExchangeData.ExchangeCardItems); i++ {
		item := p.MExchangeData.ExchangeCardItems[i]
		isdelete := false
		if item.SenderId == p.M_Player.M_DwUin {
			if item.EventType == 2 {
				if item.ApplicateStatus < 4 && item.StartTime+3600*24 <= int32(time.Now().Unix()) {
					deleteIDs = append(deleteIDs, item.AutoId)

					st := p.MsqlStruck[0]
					units := strings.Split(item.EventParam, "_")
					cardId, _ := strconv.Atoi(units[0])
					p.AddCard(&st, int32(cardId), 1, false)
					notify := msg.NotifyExchangeTimeOut{}
					notify.MExchangeCardItem = item

					agent := p.GetPlayer().GetAgentByPlayer()
					data, _ := proto.Marshal(&notify)
					G_getGameLogic().PackResInfo(agent, "NotifyExchangeTimeOut", data)

					isdelete = true
				}
			}
			if item.EventType == 3 {
				if item.ApplicateStatus < 2 && item.StartTime+3600*24 <= int32(time.Now().Unix()) {
					deleteIDs = append(deleteIDs, item.AutoId)
					notify := msg.NotifyRequestTimeOut{}
					notify.MExchangeCardItem = item

					agent := p.GetPlayer().GetAgentByPlayer()
					data, _ := proto.Marshal(&notify)
					G_getGameLogic().PackResInfo(agent, "NotifyRequestTimeOut", data)
					isdelete = true
				}
			}

		} else {

		}
		if !isdelete {
			list = append(list, item)
		}
	}
	p.MExchangeData.ExchangeCardItems = list
	p.DeleteOutlineCardExchange(deleteIDs, "t_Player_ExchangeCard_Box_Data")
	p.InitDeleteGoldCardSwap()
}

func (p *PlayerCardCollectData) DeleteOutlineCardExchange(deleteList []int32, tableName string) {
	sqlStr := "DELETE FROM " + tableName + " WHERE auto_id = ?"
	for i := 0; i < len(deleteList); i++ {

		result, err := db.SqlDb.Exec(sqlStr, deleteList[i])
		if err != nil {
			fmt.Printf("exec failed, err:%v\n", err)
			return
		}
		affectedRows, err := result.RowsAffected()
		if err != nil {
			fmt.Printf("get affected failed, err:%v\n", err)
			return
		}
		fmt.Printf("delete data success, affected rows:%d\n", affectedRows)
	}
}
func (p *PlayerCardCollectData) IsInCardActivty(ConfigActId int32) bool {
	isIn := true
	activityCfg := gamedata.GetConfigByName("Activity")
	for i := 0; i < len(G_GameLogicPtr.M_LimitActiveList); i++ {
		id := G_GameLogicPtr.M_LimitActiveList[i]
		record := activityCfg.Index(id).(*gamedata.ActivityRecord)
		if record.Type == 5 && int32(id) != ConfigActId {
			isIn = false
			break
		}
	}
	return isIn
}

func (p *PlayerCardCollectData) GetCardRecord() *gamedata.ActivityRecord {
	activityCfg := gamedata.GetConfigByName("Activity")
	for i := 0; i < len(G_GameLogicPtr.M_LimitActiveList); i++ {
		id := G_GameLogicPtr.M_LimitActiveList[i]
		record := activityCfg.Index(id).(*gamedata.ActivityRecord)
		if record.Type == 5 {
			return record

		}
	}
	return nil
}

func (p *PlayerCardCollectData) ReqExchangeCardBoxData(buf []byte) {
	req := &msg.ReqExchangeCardBoxData{}
	proto.Unmarshal(buf, req)

	p.ClearOutTimeline()
	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(&p.MExchangeData)
	G_getGameLogic().PackResInfo(agent, "ResExchangeCardBoxData", data)
}

func (p *PlayerCardCollectData) ReqDonateFriendCard(buf []byte) {
	req := &msg.ReqDonateFriendCard{}
	proto.Unmarshal(buf, req)
	res := &msg.ResDonateFriendCard{}
	st := p.FindDbSt(req.ActiveID)
	if st != nil {
		if st.RenewExchangeTime >= 5 {
			res.ResultCode = MergeConst.Protocol_Active_CardTime_NoEnough
		} else {
			if p.GetCardCnt(st, req.CardId) > 1 {

				if p.IsGoldCard(int(req.CardId)) { //是黄金卡
					if p.M_Player.GetIFGameData("PlayerCardSwapData") != nil {
						isGold := p.M_Player.GetIFGameData("PlayerCardSwapData").(*PlayerCardSwapData).IsLimitCardSwapCard(int(req.CardId))
						if isGold { //当期限时活动的黄金卡
							Cnt := p.M_Player.GetIFGameData("PlayerCardSwapData").(*PlayerCardSwapData).GetLimitCardCnt()
							if Cnt >= 2 {
								res.ResultCode = MergeConst.Protocol_Active_GoldCardTime_Cnt_NoEnouch
								agent := p.GetPlayer().GetAgentByPlayer()
								data, _ := proto.Marshal(res)
								G_getGameLogic().PackResInfo(agent, "ResDonateFriendCard", data)
								return
							} else {
								p.M_Player.GetIFGameData("PlayerCardSwapData").(*PlayerCardSwapData).AddGoldCardExchange()
								NewCnt := p.M_Player.GetIFGameData("PlayerCardSwapData").(*PlayerCardSwapData).GetLimitCardCnt()
								if NewCnt >= 2 { //达到交换上限清理其他未完成黄金卡交易
									p.NotifyDeleteGoldCardSwap()
								}
							}
						} else { //非限时活动黄金卡
							res.ResultCode = MergeConst.Protocol_Active_GoldCard_illegal_Donate
							agent := p.GetPlayer().GetAgentByPlayer()
							data, _ := proto.Marshal(res)
							G_getGameLogic().PackResInfo(agent, "ResDonateFriendCard", data)
							return
						}
					} else {
						res.ResultCode = MergeConst.Protocol_Active_GoldCard_illegal_Donate
						agent := p.GetPlayer().GetAgentByPlayer()
						data, _ := proto.Marshal(res)
						G_getGameLogic().PackResInfo(agent, "ResDonateFriendCard", data)
						return
					}
				}
				dbsql := db.SqlExchangeCardStruct{}
				dbsql.ConfigActId = int32(p.GetCardRecord().Id)
				dbsql.SenderId = req.SenderId
				dbsql.ReceiveId = req.ReceiverId
				dbsql.GroupId = 0
				dbsql.ApplicateStatus = 1
				dbsql.StartTime = int32(time.Now().Unix())
				dbsql.EventType = 1
				dbsql.EventParam = strconv.Itoa(int(req.CardId))
				insertId, err := db.FormatAllMemInsertDb(&dbsql, "t_Player_ExchangeCard_Box_Data")
				res.MExchangeCardItem = &msg.ExchangeCardItem{}
				res.MExchangeCardItem.SenderId = dbsql.SenderId
				res.MExchangeCardItem.ReceiveId = dbsql.ReceiveId
				res.MExchangeCardItem.GroupId = dbsql.GroupId
				res.MExchangeCardItem.ApplicateStatus = dbsql.ApplicateStatus
				res.MExchangeCardItem.StartTime = dbsql.StartTime
				res.MExchangeCardItem.EventType = dbsql.EventType
				res.MExchangeCardItem.EventParam = dbsql.EventParam
				res.MExchangeCardItem.ConfigActId = dbsql.ConfigActId
				res.MExchangeCardItem.AutoId = int32(insertId)

				res.ResultCode = 0
				if err == nil {
					st.RenewExchangeTime = st.RenewExchangeTime + 1
					p.DeleteOneCard(st, req.CardId)
					p.MExchangeData.ExchangeCardItems = append(p.MExchangeData.ExchangeCardItems, res.MExchangeCardItem)
					p.SaveDataFromDB("")

					EventAuid, sqlst, friendInfo := p.M_Player.GetIFGameData("PlayerFriendEventData").(*PlayerFriendEventData).NewFriendEventToDb(4, p.M_Player.M_DwUin, req.ReceiverId, []interface{}{int32(insertId), req.CardId})
					p.M_Player.GetIFGameData("PlayerFriendEventData").(*PlayerFriendEventData).NotifyNewFriendEvent(EventAuid, sqlst, friendInfo)

					player, ok := G_GameLogicPtr.M_Players[dbsql.ReceiveId]
					if ok {
						if player.GetGameData("PlayerCardCollectData") != nil {
							player.GetIFGameData("PlayerCardCollectData").(*PlayerCardCollectData).NotifyDonateFriendCard(res.MExchangeCardItem)
						}
					}
				}
			} else {
				res.ResultCode = MergeConst.Protocol_Active_Card_NoEnough
			}
		}

	} else {
		res.ResultCode = MergeConst.Protocol_Active_No_Exsit
	}
	// p.Get
	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(res)
	G_getGameLogic().PackResInfo(agent, "ResDonateFriendCard", data)
}

func (p *PlayerCardCollectData) ReqGetDonateCard(buf []byte) {
	req := &msg.ReqGetDonateCard{}
	proto.Unmarshal(buf, req)
	res := &msg.ResGetDonateCard{}

	exchange := p.GetExchangeCardItem(req.MExchangeCardItem.AutoId)
	if exchange != nil {
		units := strings.Split(req.MExchangeCardItem.EventParam, "_")
		cardId, _ := strconv.Atoi(units[0])
		p.AddCard(&p.MsqlStruck[0], int32(cardId), 1, false)
		p.DeleteExchangeCardItem(req.MExchangeCardItem.AutoId)

		dbsql := db.SqlExchangeCardStruct{}
		dbsql.ConfigActId = int32(p.GetCardRecord().Id)
		dbsql.SenderId = req.MExchangeCardItem.SenderId
		dbsql.ReceiveId = req.MExchangeCardItem.ReceiveId
		dbsql.GroupId = req.MExchangeCardItem.GroupId
		dbsql.ApplicateStatus = 2
		dbsql.StartTime = req.MExchangeCardItem.StartTime
		dbsql.EventType = 1
		dbsql.EventParam = req.MExchangeCardItem.EventParam
		dbsql.AutoId = req.MExchangeCardItem.AutoId
		db.FormatAllMemUpdateDb(&dbsql, "t_Player_ExchangeCard_Box_Data", "auto_id")

		res.MExchangeCardItem = &msg.ExchangeCardItem{}
		res.MExchangeCardItem.SenderId = dbsql.SenderId
		res.MExchangeCardItem.ReceiveId = dbsql.ReceiveId
		res.MExchangeCardItem.GroupId = dbsql.GroupId
		res.MExchangeCardItem.ApplicateStatus = dbsql.ApplicateStatus
		res.MExchangeCardItem.StartTime = dbsql.StartTime
		res.MExchangeCardItem.EventType = dbsql.EventType
		res.MExchangeCardItem.EventParam = dbsql.EventParam
		res.MExchangeCardItem.ConfigActId = dbsql.ConfigActId
		res.MExchangeCardItem.AutoId = req.MExchangeCardItem.AutoId

		player, ok := G_GameLogicPtr.M_Players[req.MExchangeCardItem.SenderId]
		if ok {
			if player.GetGameData("PlayerCardCollectData") != nil {
				player.GetIFGameData("PlayerCardCollectData").(*PlayerCardCollectData).NotifyGetDonateCard(req.MExchangeCardItem)
			}
		}
	} else {
		res.ResultCode = MergeConst.Protocol_Exchange_Card_No_Exsit
	}
	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(res)
	G_getGameLogic().PackResInfo(agent, "ResGetDonateCard", data)
}

func (p *PlayerCardCollectData) ReqRefuseExchange(buf []byte) {
	req := &msg.ReqRefuseExchange{}
	proto.Unmarshal(buf, req)
	res := &msg.ResRefuseExchange{}

	exchange := p.GetExchangeCardItem(req.MExchangeCardItem.AutoId)
	if exchange != nil {
		res.MExchangeCardItem = req.MExchangeCardItem
		if exchange.SenderId == p.M_Player.M_DwUin {
			units := strings.Split(req.MExchangeCardItem.EventParam, "_")
			cardId, _ := strconv.Atoi(units[0])
			p.AddCard(&p.MsqlStruck[0], int32(cardId), 1, false)
			timeStamp := (int64)(time.Now().Unix())
			t := time.Unix(timeStamp, 0).Local()
			zero := timeStamp - (int64)(t.Hour()*3600+t.Minute()*60+t.Second())

			timeStamp1 := (int64)(req.MExchangeCardItem.StartTime)
			t1 := time.Unix(timeStamp1, 0).Local()
			zero1 := timeStamp1 - (int64)(t1.Hour()*3600+t1.Minute()*60+t1.Second())

			if zero == zero1 {

				p.MsqlStruck[0].RenewExchangeTime = p.MsqlStruck[0].RenewExchangeTime - 1
				if p.MsqlStruck[0].RenewExchangeTime < 0 {
					p.MsqlStruck[0].RenewExchangeTime = 0
				}
				p.SaveDataFromDB("")
			}

			EventAI := p.M_Player.GetIFGameData("PlayerFriendEventData").(*PlayerFriendEventData).DeleteEventDbData(p.M_Player.M_DwUin, 6, req.MExchangeCardItem.AutoId)
			p.M_Player.GetIFGameData("PlayerFriendEventData").(*PlayerFriendEventData).DeleteLocalDataByAutoId(EventAI)

			player, ok := G_GameLogicPtr.M_Players[req.MExchangeCardItem.ReceiveId]
			if ok {
				if player.GetGameData("PlayerCardCollectData") != nil {
					player.GetIFGameData("PlayerCardCollectData").(*PlayerCardCollectData).NOtifyReceiveRefuseExchange(req.MExchangeCardItem)
				}
			} else {
				sqlStr := "SELECT * FROM t_player_card_data WHERE dwUin = ?"
				MsqlStruck := db.SqlCardCollectStruct{}
				units := strings.Split(req.MExchangeCardItem.EventParam, "_")
				cardId, _ := strconv.Atoi(units[1])
				err := db.SqlDb.Get(&MsqlStruck, sqlStr, req.MExchangeCardItem.ReceiveId)
				if err != nil {

				} else {
					if MsqlStruck.CardInfo != "" {
						units := strings.Split(MsqlStruck.CardInfo, ";")

						for i := 0; i < len(units); i++ {
							items := strings.Split(units[i], ",")
							k, _ := strconv.Atoi(items[0])
							cnt, _ := strconv.Atoi(items[1])
							if k == int(cardId) {
								cnt = cnt + 1
								units[i] = items[0] + "," + strconv.Itoa(cnt)
								break
							}
						}
						MsqlStruck.CardInfo = strings.Join(units, ";")
					}
					db.FormatAllMemUpdateDb(&MsqlStruck, "t_player_card_data", "dwUin")
				}

			}
		} else {
			EventAI := p.M_Player.GetIFGameData("PlayerFriendEventData").(*PlayerFriendEventData).DeleteEventDbData(p.M_Player.M_DwUin, 8, req.MExchangeCardItem.AutoId)
			p.M_Player.GetIFGameData("PlayerFriendEventData").(*PlayerFriendEventData).DeleteLocalDataByAutoId(EventAI)

			player, ok := G_GameLogicPtr.M_Players[req.MExchangeCardItem.SenderId]
			if ok {
				if player.GetGameData("PlayerCardCollectData") != nil {
					player.GetIFGameData("PlayerCardCollectData").(*PlayerCardCollectData).NOtifyRefuseExchange(req.MExchangeCardItem)
					player.GetIFGameData("PlayerCardCollectData").(*PlayerCardCollectData).DeleteExchangeCardItem(req.MExchangeCardItem.AutoId)
				}
			} else {
				sqlStr := "SELECT * FROM t_player_card_data WHERE dwUin = ?"
				MsqlStruck := db.SqlCardCollectStruct{}
				units := strings.Split(req.MExchangeCardItem.EventParam, "_")
				cardId, _ := strconv.Atoi(units[0])
				err := db.SqlDb.Get(&MsqlStruck, sqlStr, req.MExchangeCardItem.SenderId)
				if err != nil {

				} else {
					if MsqlStruck.CardInfo != "" {
						units := strings.Split(MsqlStruck.CardInfo, ";")

						for i := 0; i < len(units); i++ {
							items := strings.Split(units[i], ",")
							k, _ := strconv.Atoi(items[0])
							cnt, _ := strconv.Atoi(items[1])
							if k == int(cardId) {
								cnt = cnt + 1
								units[i] = items[0] + "," + strconv.Itoa(cnt)
								break
							}
						}
						MsqlStruck.CardInfo = strings.Join(units, ";")
					}

				}

				timeStamp := (int64)(time.Now().Unix())
				t := time.Unix(timeStamp, 0).Local()
				zero := timeStamp - (int64)(t.Hour()*3600+t.Minute()*60+t.Second())

				timeStamp1 := (int64)(req.MExchangeCardItem.StartTime)
				t1 := time.Unix(timeStamp1, 0).Local()
				zero1 := timeStamp1 - (int64)(t1.Hour()*3600+t1.Minute()*60+t1.Second())

				if zero == zero1 && err == nil {
					MsqlStruck.RenewExchangeTime -= 1
				}
				db.FormatAllMemUpdateDb(&MsqlStruck, "t_player_card_data", "dwUin")
			}
		}
		res.RenewExchangeTime = p.MsqlStruck[0].RenewExchangeTime
		p.DeleteExchangeCardItem(req.MExchangeCardItem.AutoId)
		sqlStr := "DELETE FROM " + "t_Player_ExchangeCard_Box_Data" + " WHERE auto_id = ?"
		db.SqlDb.Exec(sqlStr, req.MExchangeCardItem.AutoId)

	} else {
		res.ResultCode = MergeConst.Protocol_Exchange_Card_No_Exsit
	}
	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(res)
	G_getGameLogic().PackResInfo(agent, "ResRefuseExchange", data)
}

func (p *PlayerCardCollectData) NOtifyReceiveRefuseExchange(st *msg.ExchangeCardItem) {
	units := strings.Split(st.EventParam, "_")
	cardId, _ := strconv.Atoi(units[1])
	p.AddCard(&p.MsqlStruck[0], int32(cardId), 1, false)

	p.DeleteExchangeCardItem(st.AutoId)
	p.SaveDataFromDB("")

	notify := &msg.NOtifyRefuseExchange{}
	notify.MExchangeCardItem = st
	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(notify)
	G_getGameLogic().PackResInfo(agent, "NOtifyRefuseExchange", data)
}

func (p *PlayerCardCollectData) NOtifyRefuseExchange(st *msg.ExchangeCardItem) {
	notify := &msg.NOtifyRefuseExchange{}
	notify.MExchangeCardItem = st

	units := strings.Split(st.EventParam, "_")
	cardId, _ := strconv.Atoi(units[0])
	p.AddCard(&p.MsqlStruck[0], int32(cardId), 1, false)

	timeStamp := (int64)(time.Now().Unix())
	t := time.Unix(timeStamp, 0).Local()
	zero := timeStamp - (int64)(t.Hour()*3600+t.Minute()*60+t.Second())

	timeStamp1 := (int64)(st.StartTime)
	t1 := time.Unix(timeStamp1, 0).Local()
	zero1 := timeStamp1 - (int64)(t1.Hour()*3600+t1.Minute()*60+t1.Second())
	// p.DeleteExchangeCardItem(st.AutoId)
	if zero == zero1 {
		p.MsqlStruck[0].RenewExchangeTime = p.MsqlStruck[0].RenewExchangeTime - 1

		if p.MsqlStruck[0].RenewExchangeTime < 0 {
			p.MsqlStruck[0].RenewExchangeTime = 0
		}
		p.SaveDataFromDB("")
	}
	notify.RenewExchangeTime = p.MsqlStruck[0].RenewExchangeTime
	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(notify)
	G_getGameLogic().PackResInfo(agent, "NOtifyRefuseExchange", data)
}

func (p *PlayerCardCollectData) NotifyGetDonateCard(st *msg.ExchangeCardItem) {
	notify := &msg.NotifyGetDonateCard{}
	notify.MExchangeCardItem = st

	p.DeleteExchangeCardItem(st.AutoId)

	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(notify)
	G_getGameLogic().PackResInfo(agent, "NotifyGetDonateCard", data)
}

func (p *PlayerCardCollectData) GenExchangeIncID() int32 {
	dbsql := db.SqlExchangeCardReqIncStruct{}
	dbsql.StartTime = int32(time.Now().Unix())

	insertId, _ := db.FormatAllMemInsertDb(&dbsql, "t_Player_ExchangeCard_ReqInc")
	return int32(insertId)
}

func (p *PlayerCardCollectData) ReqRequestCard(buf []byte) {
	req := &msg.ReqRequestCard{}
	proto.Unmarshal(buf, req)
	res := &msg.ResRequestCard{}
	st := p.FindDbSt(req.ActiveID)
	res.ExchangeCardItems = []*msg.ExchangeCardItem{}
	if st != nil {
		if st.RenewRequestTime >= 2 {
			res.ResultCode = MergeConst.Protocol_Active_CardTime_NoEnough
		} else {
			GroupId := p.GenExchangeIncID()
			st.RenewRequestTime = st.RenewRequestTime + 1
			db.FormatAllMemUpdateDb(st, "t_player_card_data", "ActiveID")
			for i := 0; i < len(req.ReceiverIds); i++ {
				dbsql := db.SqlExchangeCardStruct{}
				dbsql.ConfigActId = int32(p.GetCardRecord().Id)
				dbsql.SenderId = req.SenderId
				dbsql.ReceiveId = req.ReceiverIds[i]
				dbsql.GroupId = GroupId
				dbsql.ApplicateStatus = 1
				dbsql.StartTime = int32(time.Now().Unix())
				dbsql.EventType = 3
				dbsql.EventParam = strconv.Itoa(int(req.CardId))
				insertId, _ := db.FormatAllMemInsertDb(&dbsql, "t_Player_ExchangeCard_Box_Data")

				MExchangeCardItem := &msg.ExchangeCardItem{}
				MExchangeCardItem.SenderId = dbsql.SenderId
				MExchangeCardItem.ReceiveId = dbsql.ReceiveId
				MExchangeCardItem.GroupId = dbsql.GroupId
				MExchangeCardItem.ApplicateStatus = dbsql.ApplicateStatus
				MExchangeCardItem.StartTime = dbsql.StartTime
				MExchangeCardItem.EventType = dbsql.EventType
				MExchangeCardItem.EventParam = dbsql.EventParam
				MExchangeCardItem.ConfigActId = dbsql.ConfigActId
				MExchangeCardItem.AutoId = int32(insertId)

				p.MExchangeData.ExchangeCardItems = append(p.MExchangeData.ExchangeCardItems, MExchangeCardItem)
				res.ExchangeCardItems = append(res.ExchangeCardItems, MExchangeCardItem)

				EventAuid, sqlst, friendInfo := p.M_Player.GetIFGameData("PlayerFriendEventData").(*PlayerFriendEventData).NewFriendEventToDb(5, p.M_Player.M_DwUin, dbsql.ReceiveId, []interface{}{int32(insertId), req.CardId})
				p.M_Player.GetIFGameData("PlayerFriendEventData").(*PlayerFriendEventData).NotifyNewFriendEvent(EventAuid, sqlst, friendInfo)

				player, ok := G_GameLogicPtr.M_Players[dbsql.ReceiveId]
				if ok {
					if player.GetGameData("PlayerCardCollectData") != nil {
						player.GetIFGameData("PlayerCardCollectData").(*PlayerCardCollectData).NotifyRequestCard(MExchangeCardItem)
					}
				}

			}
		}

	} else {
		res.ResultCode = MergeConst.Protocol_Active_No_Exsit
	}
	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(res)
	G_getGameLogic().PackResInfo(agent, "ResRequestCard", data)

}
func (p *PlayerCardCollectData) NotifyRequestCard(MExchangeCardItem *msg.ExchangeCardItem) {

	p.MExchangeData.ExchangeCardItems = append(p.MExchangeData.ExchangeCardItems, MExchangeCardItem)

	notify := &msg.NotifyRequestCard{}
	notify.ExchangeCardItems = MExchangeCardItem
	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(notify)
	G_getGameLogic().PackResInfo(agent, "NotifyRequestCard", data)

}

func (p *PlayerCardCollectData) NotifyFriendCompleteRequestCard(ComId int32, GroupId int32) {
	sqlStr := "SELECT * FROM t_Player_ExchangeCard_Box_Data WHERE GroupId = ?"
	MsqlExchanges := []db.SqlExchangeCardStruct{}

	if err := db.SqlDb.Select(&MsqlExchanges, sqlStr, GroupId); err != nil {

	} else {
		for i := 0; i < len(MsqlExchanges); i++ {
			if MsqlExchanges[i].ReceiveId == ComId {

			} else {
				sqlStr := "DELETE FROM " + "t_Player_ExchangeCard_Box_Data" + " WHERE auto_id = ?"
				db.SqlDb.Exec(sqlStr, MsqlExchanges[i].AutoId)

				player, ok := G_GameLogicPtr.M_Players[MsqlExchanges[i].ReceiveId]
				if ok {
					if player.GetGameData("PlayerCardCollectData") != nil {
						player.GetIFGameData("PlayerCardCollectData").(*PlayerCardCollectData).NotifyHaveFriendCompleteReq(MsqlExchanges[i].AutoId)
					}
				}
			}
		}
	}

}

func (p *PlayerCardCollectData) ReqGetRequestCard(buf []byte) {
	req := &msg.ReqGetRequestCard{}
	proto.Unmarshal(buf, req)
	res := &msg.ResGetRequestCard{}

	ExchangeItem := p.GetExchangeCardItem(req.ExchangeCardItems.AutoId)

	if ExchangeItem != nil {
		res.ExchangeCardItems = req.ExchangeCardItems
		units := strings.Split(req.ExchangeCardItems.EventParam, "_")
		excardId, _ := strconv.Atoi(units[0])

		p.AddCard(&p.MsqlStruck[0], int32(excardId), 1, false)
		p.DeleteExchangeCardItem(req.ExchangeCardItems.AutoId)
		sqlStr := "DELETE FROM " + "t_Player_ExchangeCard_Box_Data" + " WHERE auto_id = ?"
		db.SqlDb.Exec(sqlStr, req.ExchangeCardItems.AutoId)

		EventAI := p.M_Player.GetIFGameData("PlayerFriendEventData").(*PlayerFriendEventData).DeleteEventDbData(p.M_Player.M_DwUin, 7, req.ExchangeCardItems.AutoId)
		p.M_Player.GetIFGameData("PlayerFriendEventData").(*PlayerFriendEventData).DeleteLocalDataByAutoId(EventAI)

	} else {
		res.ResultCode = MergeConst.Protocol_Active_CardTime_Outline
		res.ExchangeCardItems = req.ExchangeCardItems
	}

	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(res)
	G_getGameLogic().PackResInfo(agent, "ResGetRequestCard", data)
}

func (p *PlayerCardCollectData) NotifyHaveFriendCompleteReq(AutoId int32) {

	p.DeleteExchangeCardItem(AutoId)

	notify := &msg.NotifyHaveFriendCompleteReq{}
	notify.AutoId = AutoId
	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(notify)
	G_getGameLogic().PackResInfo(agent, "NotifyHaveFriendCompleteReq", data)
}

func (p *PlayerCardCollectData) ReqCompleteRequestCard(buf []byte) {
	req := &msg.ReqCompleteRequestCard{}
	proto.Unmarshal(buf, req)
	res := &msg.ResCompleteRequestCard{}

	ExchangeItem := p.GetExchangeCardItem(req.ExchangeCardItems.AutoId)
	st := &p.MsqlStruck[0]
	if ExchangeItem != nil {
		units := strings.Split(req.ExchangeCardItems.EventParam, "_")
		excardId, _ := strconv.Atoi(units[0])

		if ExchangeItem.StartTime+3600*24 <= int32(time.Now().Unix()) {
			res.ResultCode = MergeConst.Protocol_Active_CardTime_Outline
			res.ExchangeCardItems = req.ExchangeCardItems
			p.DeleteExchangeCardItem(req.ExchangeCardItems.AutoId)
		} else {

			res.ExchangeCardItems = &msg.ExchangeCardItem{}
			dbsql := db.SqlExchangeCardStruct{}
			dbsql.ConfigActId = int32(p.GetCardRecord().Id)
			dbsql.SenderId = req.ExchangeCardItems.SenderId
			dbsql.ReceiveId = req.ExchangeCardItems.ReceiveId
			dbsql.GroupId = req.ExchangeCardItems.GroupId
			dbsql.ApplicateStatus = 2
			dbsql.StartTime = req.ExchangeCardItems.StartTime
			dbsql.EventType = req.ExchangeCardItems.EventType
			dbsql.EventParam = req.ExchangeCardItems.EventParam
			dbsql.AutoId = req.ExchangeCardItems.AutoId

			ExchangeItem.ApplicateStatus = 2
			err := db.FormatAllMemUpdateDb(&dbsql, "t_Player_ExchangeCard_Box_Data", "auto_id")
			res.ExchangeCardItems.SenderId = dbsql.SenderId
			res.ExchangeCardItems.ReceiveId = dbsql.ReceiveId
			res.ExchangeCardItems.GroupId = dbsql.GroupId
			res.ExchangeCardItems.ApplicateStatus = dbsql.ApplicateStatus
			res.ExchangeCardItems.StartTime = dbsql.StartTime
			res.ExchangeCardItems.EventType = dbsql.EventType
			res.ExchangeCardItems.EventParam = dbsql.EventParam
			res.ExchangeCardItems.ConfigActId = dbsql.ConfigActId
			res.ExchangeCardItems.AutoId = dbsql.AutoId

			if err == nil {
				p.AddCard(st, int32(excardId), -1, false)
				p.SaveDataFromDB("")

				EventAuid, sqlst, friendInfo := p.M_Player.GetIFGameData("PlayerFriendEventData").(*PlayerFriendEventData).NewFriendEventToDb(7, dbsql.SenderId, dbsql.ReceiveId, []interface{}{dbsql.AutoId, int32(excardId)})

				player, ok := G_GameLogicPtr.M_Players[dbsql.SenderId]
				if ok {
					if player.GetGameData("PlayerCardCollectData") != nil {
						player.GetIFGameData("PlayerCardCollectData").(*PlayerCardCollectData).NotifyCompleteRequestCard(res.ExchangeCardItems)
					}
					if player.GetGameData("PlayerFriendEventData") != nil {
						player.GetIFGameData("PlayerFriendEventData").(*PlayerFriendEventData).NotifyNewFriendEvent(EventAuid, sqlst, friendInfo)
					}
				}
				p.NotifyFriendCompleteRequestCard(dbsql.ReceiveId, dbsql.GroupId)
			}

		}
	} else {
		res.ResultCode = MergeConst.Protocol_Active_CardTime_Outline
		res.ExchangeCardItems = req.ExchangeCardItems
	}

	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(res)
	G_getGameLogic().PackResInfo(agent, "ResCompleteRequestCard", data)
}

func (p *PlayerCardCollectData) ReqRefuseRequestCard(buf []byte) {
	req := &msg.ReqRefuseRequestCard{}
	proto.Unmarshal(buf, req)
	res := &msg.ResRefuseRequestCard{}

	ExchangeItem := p.GetExchangeCardItem(req.ExchangeCardItems.AutoId)

	if ExchangeItem != nil {
		p.DeleteExchangeCardItem(req.ExchangeCardItems.AutoId)
		res.ExchangeCardItems = req.ExchangeCardItems
		sqlStr := "DELETE FROM " + "t_Player_ExchangeCard_Box_Data" + " WHERE auto_id = ?"
		db.SqlDb.Exec(sqlStr, req.ExchangeCardItems.AutoId)
		player, ok := G_GameLogicPtr.M_Players[req.ExchangeCardItems.SenderId]
		if ok {
			if player.GetGameData("PlayerCardCollectData") != nil {
				player.GetIFGameData("PlayerCardCollectData").(*PlayerCardCollectData).NotifyRefuseRequestCard(req.ExchangeCardItems)
			}
		} else {
			sqlStr := "SELECT * FROM t_player_card_data WHERE dwUin = ?"
			MsqlStruck := db.SqlCardCollectStruct{}

			err := db.SqlDb.Get(&MsqlStruck, sqlStr, req.ExchangeCardItems.SenderId)
			if err != nil {

			} else {

			}

			timeStamp := (int64)(time.Now().Unix())
			t := time.Unix(timeStamp, 0).Local()
			zero := timeStamp - (int64)(t.Hour()*3600+t.Minute()*60+t.Second())

			timeStamp1 := (int64)(req.ExchangeCardItems.StartTime)
			t1 := time.Unix(timeStamp1, 0).Local()
			zero1 := timeStamp1 - (int64)(t1.Hour()*3600+t1.Minute()*60+t1.Second())

			if zero == zero1 && err == nil {
				MsqlStruck.RenewRequestTime -= 1
				if MsqlStruck.RenewRequestTime < 0 {
					MsqlStruck.RenewRequestTime = 0
				}
			}
			db.FormatAllMemUpdateDb(&MsqlStruck, "t_player_card_data", "dwUin")
		}

	} else {

	}
	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(res)
	G_getGameLogic().PackResInfo(agent, "ResRefuseRequestCard", data)
}

func (p *PlayerCardCollectData) ReqExchangeCard(buf []byte) {
	req := &msg.ReqExchangeCard{}
	proto.Unmarshal(buf, req)
	res := &msg.ResExchangeCard{}
	st := p.FindDbSt(req.ActiveID)
	if st != nil {
		if st.RenewExchangeTime >= 5 {
			res.ResultCode = MergeConst.Protocol_Active_CardTime_NoEnough
		} else {
			if p.GetCardCnt(st, req.CardId) > 1 {
				if p.IsGoldCard(int(req.CardId)) { //是黄金卡
					if p.M_Player.GetIFGameData("PlayerCardSwapData") != nil {
						isGold := p.M_Player.GetIFGameData("PlayerCardSwapData").(*PlayerCardSwapData).IsLimitCardSwapCard(int(req.CardId))
						if isGold { //当期限时活动的黄金卡
							Cnt := p.M_Player.GetIFGameData("PlayerCardSwapData").(*PlayerCardSwapData).GetLimitCardCnt()
							if Cnt >= 2 {
								res.ResultCode = MergeConst.Protocol_Active_GoldCardTime_Cnt_NoEnouch
								agent := p.GetPlayer().GetAgentByPlayer()
								data, _ := proto.Marshal(res)
								G_getGameLogic().PackResInfo(agent, "ResExchangeCard", data)
								return
							}
						} else { //非限时活动黄金卡
							res.ResultCode = MergeConst.Protocol_Active_GoldCard_illegal_Swap
							agent := p.GetPlayer().GetAgentByPlayer()
							data, _ := proto.Marshal(res)
							G_getGameLogic().PackResInfo(agent, "ResExchangeCard", data)
							return
						}
					} else {
						res.ResultCode = MergeConst.Protocol_Active_GoldCard_illegal_Swap
						agent := p.GetPlayer().GetAgentByPlayer()
						data, _ := proto.Marshal(res)
						G_getGameLogic().PackResInfo(agent, "ResExchangeCard", data)
						return
					}
				}
				res.MExchangeCardItem = &msg.ExchangeCardItem{}
				dbsql := db.SqlExchangeCardStruct{}
				dbsql.ConfigActId = int32(p.GetCardRecord().Id)
				dbsql.SenderId = req.SenderId
				dbsql.ReceiveId = req.ReceiverId
				dbsql.GroupId = 0
				dbsql.ApplicateStatus = 1
				dbsql.StartTime = int32(time.Now().Unix())
				dbsql.EventType = 2
				dbsql.EventParam = strconv.Itoa(int(req.CardId))
				insertId, err := db.FormatAllMemInsertDb(&dbsql, "t_Player_ExchangeCard_Box_Data")

				res.MExchangeCardItem.SenderId = dbsql.SenderId
				res.MExchangeCardItem.ReceiveId = dbsql.ReceiveId
				res.MExchangeCardItem.GroupId = dbsql.GroupId
				res.MExchangeCardItem.ApplicateStatus = dbsql.ApplicateStatus
				res.MExchangeCardItem.StartTime = dbsql.StartTime
				res.MExchangeCardItem.EventType = dbsql.EventType
				res.MExchangeCardItem.EventParam = dbsql.EventParam
				res.MExchangeCardItem.ConfigActId = dbsql.ConfigActId
				res.MExchangeCardItem.AutoId = int32(insertId)
				res.ResultCode = 0
				if err == nil {
					st.RenewExchangeTime = st.RenewExchangeTime + 1
					p.DeleteOneCard(st, req.CardId)
					p.MExchangeData.ExchangeCardItems = append(p.MExchangeData.ExchangeCardItems, res.MExchangeCardItem)
					p.SaveDataFromDB("")

					EventAuid, sqlst, friendInfo := p.M_Player.GetIFGameData("PlayerFriendEventData").(*PlayerFriendEventData).NewFriendEventToDb(3, p.M_Player.M_DwUin, req.ReceiverId, []interface{}{int32(insertId), req.CardId})
					p.M_Player.GetIFGameData("PlayerFriendEventData").(*PlayerFriendEventData).NotifyNewFriendEvent(EventAuid, sqlst, friendInfo)

					EventAuid1, sqlst1, friendInfo1 := p.M_Player.GetIFGameData("PlayerFriendEventData").(*PlayerFriendEventData).NewFriendEventToDb(8, req.ReceiverId, p.M_Player.M_DwUin, []interface{}{int32(insertId), req.CardId})
					player, ok := G_GameLogicPtr.M_Players[dbsql.ReceiveId]
					if ok {
						if player.GetGameData("PlayerCardCollectData") != nil {
							player.GetIFGameData("PlayerCardCollectData").(*PlayerCardCollectData).NotifyExchangeCard(res.MExchangeCardItem)
						}
						if player.GetGameData("PlayerFriendEventData") != nil {
							player.GetIFGameData("PlayerFriendEventData").(*PlayerFriendEventData).NotifyNewFriendEvent(EventAuid1, sqlst1, friendInfo1)
						}
					}
				}
			} else {
				res.ResultCode = MergeConst.Protocol_Active_Card_NoEnough
			}
		}

	} else {
		res.ResultCode = MergeConst.Protocol_Active_No_Exsit
	}

	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(res)
	G_getGameLogic().PackResInfo(agent, "ResExchangeCard", data)
}

func (p *PlayerCardCollectData) NotifyRefuseRequestCard(st *msg.ExchangeCardItem) {
	notify := &msg.NotifyRefuseRequestCard{}
	notify.ExchangeCardItems = st

	timeStamp := (int64)(time.Now().Unix())
	t := time.Unix(timeStamp, 0).Local()
	zero := timeStamp - (int64)(t.Hour()*3600+t.Minute()*60+t.Second())

	timeStamp1 := (int64)(st.StartTime)
	t1 := time.Unix(timeStamp1, 0).Local()
	zero1 := timeStamp1 - (int64)(t1.Hour()*3600+t1.Minute()*60+t1.Second())

	if zero == zero1 {
		p.MsqlStruck[0].RenewRequestTime = p.MsqlStruck[0].RenewRequestTime - 1

		if p.MsqlStruck[0].RenewRequestTime < 0 {
			p.MsqlStruck[0].RenewRequestTime = 0
		}
		p.SaveDataFromDB("")
	}

	notify.RenewRequestTime = p.MsqlStruck[0].RenewRequestTime
	p.DeleteExchangeCardItem(st.AutoId)
	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(notify)
	G_getGameLogic().PackResInfo(agent, "NotifyRefuseRequestCard", data)
}

func (p *PlayerCardCollectData) NotifyExchangeCard(st *msg.ExchangeCardItem) {
	notify := &msg.NotifyExchangeCard{}
	notify.MExchangeCardItem = st

	p.MExchangeData.ExchangeCardItems = append(p.MExchangeData.ExchangeCardItems, st)
	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(notify)
	G_getGameLogic().PackResInfo(agent, "NotifyExchangeCard", data)
}

func (p *PlayerCardCollectData) NotifyDonateFriendCard(st *msg.ExchangeCardItem) {
	notify := &msg.NotifyDonateFriendCard{}
	notify.MExchangeCardItem = st
	p.MExchangeData.ExchangeCardItems = append(p.MExchangeData.ExchangeCardItems, st)

	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(notify)
	G_getGameLogic().PackResInfo(agent, "NotifyDonateFriendCard", data)
}

func (p *PlayerCardCollectData) NotifyReceiptCard(st *msg.ExchangeCardItem) {
	notify := &msg.NotifyReceiptCard{}
	notify.MExchangeCardItem = st

	index := p.GetExchangeCardItemIndex(st.AutoId)
	if index >= 0 {
		p.MExchangeData.ExchangeCardItems[index] = st
	}

	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(notify)
	G_getGameLogic().PackResInfo(agent, "NotifyReceiptCard", data)
}

func (p *PlayerCardCollectData) NotifyCompleteExchangeCard(st *msg.ExchangeCardItem) {
	notify := &msg.NotifyCompleteExchangeCard{}
	notify.MExchangeCardItem = st

	index := p.GetExchangeCardItemIndex(st.AutoId)
	if index >= 0 {
		p.MExchangeData.ExchangeCardItems[index] = st
	}

	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(notify)
	G_getGameLogic().PackResInfo(agent, "NotifyCompleteExchangeCard", data)
}

func (p *PlayerCardCollectData) NotifyCompleteRequestCard(st *msg.ExchangeCardItem) {
	notify := &msg.NotifyCompleteRequestCard{}
	notify.ExchangeCardItems = st

	index := p.GetExchangeCardItemIndex(st.AutoId)
	if index >= 0 {
		p.MExchangeData.ExchangeCardItems[index] = st
	}

	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(notify)
	G_getGameLogic().PackResInfo(agent, "NotifyCompleteRequestCard", data)
}
func (p *PlayerCardCollectData) NotifyGetExchangeCard(st *msg.ExchangeCardItem) {
	notify := &msg.NotifyGetExchangeCard{}
	notify.MExchangeCardItem = st

	p.DeleteExchangeCardItem(st.AutoId)

	sqlStr := "DELETE FROM " + "t_Player_ExchangeCard_Box_Data" + " WHERE auto_id = ?"
	db.SqlDb.Exec(sqlStr, st.AutoId)

	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(notify)
	G_getGameLogic().PackResInfo(agent, "NotifyGetExchangeCard", data)
}

func (p *PlayerCardCollectData) GetExchangeCardItem(AutoId int32) *msg.ExchangeCardItem {
	for i := 0; i < len(p.MExchangeData.ExchangeCardItems); i++ {
		if p.MExchangeData.ExchangeCardItems[i].AutoId == AutoId {
			return p.MExchangeData.ExchangeCardItems[i]
		}
	}
	return nil
}

func (p *PlayerCardCollectData) GetExchangeCardItemIndex(AutoId int32) int {
	index := -1
	for i := 0; i < len(p.MExchangeData.ExchangeCardItems); i++ {
		if p.MExchangeData.ExchangeCardItems[i].AutoId == AutoId {
			return i
		}
	}
	return index
}

func (p *PlayerCardCollectData) DeleteExchangeCardItem(AutoId int32) {
	for i := 0; i < len(p.MExchangeData.ExchangeCardItems); i++ {
		if p.MExchangeData.ExchangeCardItems[i].AutoId == AutoId {
			p.MExchangeData.ExchangeCardItems = append(p.MExchangeData.ExchangeCardItems[:i], p.MExchangeData.ExchangeCardItems[i+1:]...)
			break
		}
	}
}

func (p *PlayerCardCollectData) ReqReceiptCard(buf []byte) {
	req := &msg.ReqReceiptCard{}
	proto.Unmarshal(buf, req)
	res := &msg.ResReceiptCard{}
	ExchangeItem := p.GetExchangeCardItem(req.MExchangeCardItem.AutoId)
	st := &p.MsqlStruck[0]
	if ExchangeItem != nil {
		units := strings.Split(req.MExchangeCardItem.EventParam, "_")
		cardId, _ := strconv.Atoi(units[0])
		excardId, _ := strconv.Atoi(units[1])
		if ExchangeItem.StartTime+3600*24 <= int32(time.Now().Unix()) {
			res.ResultCode = MergeConst.Protocol_Active_CardTime_Outline
			res.MExchangeCardItem = req.MExchangeCardItem
			p.DeleteExchangeCardItem(req.MExchangeCardItem.AutoId)
		} else {

			if p.GetCardCnt(st, int32(excardId)) > 1 {
				res.MExchangeCardItem = &msg.ExchangeCardItem{}
				dbsql := db.SqlExchangeCardStruct{}
				dbsql.ConfigActId = int32(p.GetCardRecord().Id)
				dbsql.SenderId = req.MExchangeCardItem.SenderId
				dbsql.ReceiveId = req.MExchangeCardItem.ReceiveId
				dbsql.GroupId = req.MExchangeCardItem.GroupId
				dbsql.ApplicateStatus = 2
				dbsql.StartTime = req.MExchangeCardItem.StartTime
				dbsql.EventType = 2
				dbsql.EventParam = req.MExchangeCardItem.EventParam
				dbsql.AutoId = req.MExchangeCardItem.AutoId

				err := db.FormatAllMemUpdateDb(&dbsql, "t_Player_ExchangeCard_Box_Data", "auto_id")
				res.MExchangeCardItem.SenderId = dbsql.SenderId
				res.MExchangeCardItem.ReceiveId = dbsql.ReceiveId
				res.MExchangeCardItem.GroupId = dbsql.GroupId
				res.MExchangeCardItem.ApplicateStatus = dbsql.ApplicateStatus
				res.MExchangeCardItem.StartTime = dbsql.StartTime
				res.MExchangeCardItem.EventType = dbsql.EventType
				res.MExchangeCardItem.EventParam = dbsql.EventParam
				res.MExchangeCardItem.ConfigActId = dbsql.ConfigActId
				res.MExchangeCardItem.AutoId = dbsql.AutoId

				if err == nil {
					p.DeleteOneCard(st, int32(excardId))
					p.SaveDataFromDB("")
					EventAI := p.M_Player.GetIFGameData("PlayerFriendEventData").(*PlayerFriendEventData).DeleteEventDbData(p.M_Player.M_DwUin, 8, req.MExchangeCardItem.AutoId)
					p.M_Player.GetIFGameData("PlayerFriendEventData").(*PlayerFriendEventData).DeleteLocalDataByAutoId(EventAI)

					EventAuid, sqlst, friendInfo := p.M_Player.GetIFGameData("PlayerFriendEventData").(*PlayerFriendEventData).NewFriendEventToDb(6, dbsql.SenderId, dbsql.ReceiveId, []interface{}{dbsql.AutoId, int32(excardId), int32(cardId)})
					EventAuid1, sqlst1, friendInfo1 := p.M_Player.GetIFGameData("PlayerFriendEventData").(*PlayerFriendEventData).NewFriendEventToDb(9, dbsql.ReceiveId, dbsql.SenderId, []interface{}{dbsql.AutoId, int32(excardId), int32(cardId)})
					p.M_Player.GetIFGameData("PlayerFriendEventData").(*PlayerFriendEventData).NotifyNewFriendEvent(EventAuid1, sqlst1, friendInfo1)
					player, ok := G_GameLogicPtr.M_Players[dbsql.SenderId]
					if ok {
						if player.GetGameData("PlayerCardCollectData") != nil {
							player.GetIFGameData("PlayerCardCollectData").(*PlayerCardCollectData).NotifyReceiptCard(res.MExchangeCardItem)
						}
						if player.GetGameData("PlayerFriendEventData") != nil {
							player.GetIFGameData("PlayerFriendEventData").(*PlayerFriendEventData).NotifyNewFriendEvent(EventAuid, sqlst, friendInfo)
						}
					}
				}

			} else {
				res.ResultCode = MergeConst.Protocol_Active_CardFragment_NoEnough
			}

		}
	} else {
		res.ResultCode = MergeConst.Protocol_Active_CardTime_Outline
	}

	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(res)
	G_getGameLogic().PackResInfo(agent, "ResReceiptCard", data)
}

func (p *PlayerCardCollectData) IsGoldCard(cardId int) bool {
	CardDetailCfg := gamedata.GetConfigByName("CardDetailCfg")
	record := CardDetailCfg.Index(cardId).(*gamedata.CardDetailRecord)
	return record.IsGold == 1
}

func (p *PlayerCardCollectData) InitDeleteGoldCardSwap() {
	DeleteIds := []int32{}
	temp := []*msg.ExchangeCardItem{}
	for i := 0; i < len(p.MExchangeData.ExchangeCardItems); i++ {
		Item := p.MExchangeData.ExchangeCardItems[i]
		if Item.EventType == 2 {
			if Item.SenderId == p.M_Player.M_DwUin {
				if Item.ApplicateStatus == 1 {
					units := strings.Split(Item.EventParam, "_")
					cardId, _ := strconv.Atoi(units[0])
					if p.IsGoldCard(cardId) { //是黄金卡
						if p.M_Player.GetIFGameData("PlayerCardSwapData") != nil {
							isGold := p.M_Player.GetIFGameData("PlayerCardSwapData").(*PlayerCardSwapData).IsLimitCardSwapCard(cardId)
							if !isGold { //过期黄金卡交换
								DeleteIds = append(DeleteIds, Item.AutoId)
								EventAI := p.M_Player.GetIFGameData("PlayerFriendEventData").(*PlayerFriendEventData).DeleteEventDbData(Item.ReceiveId, 8, Item.AutoId)
								p.M_Player.GetIFGameData("PlayerFriendEventData").(*PlayerFriendEventData).DeleteLocalDataByAutoId(EventAI)
								p.NOtifyRefuseExchange(Item)

								continue
							}
						} else {
							DeleteIds = append(DeleteIds, Item.AutoId)
							EventAI := p.M_Player.GetIFGameData("PlayerFriendEventData").(*PlayerFriendEventData).DeleteEventDbData(Item.ReceiveId, 8, Item.AutoId)
							p.M_Player.GetIFGameData("PlayerFriendEventData").(*PlayerFriendEventData).DeleteLocalDataByAutoId(EventAI)
							p.NOtifyRefuseExchange(Item)

							continue
						}
					}
				}
				if Item.ApplicateStatus == 2 {
					units := strings.Split(Item.EventParam, "_")
					cardId, _ := strconv.Atoi(units[0])

					if p.IsGoldCard(cardId) { //是黄金卡
						if p.M_Player.GetIFGameData("PlayerCardSwapData") != nil {
							isGold := p.M_Player.GetIFGameData("PlayerCardSwapData").(*PlayerCardSwapData).IsLimitCardSwapCard(cardId)
							if !isGold { //过期黄金卡交换
								DeleteIds = append(DeleteIds, Item.AutoId)
								EventAI := p.M_Player.GetIFGameData("PlayerFriendEventData").(*PlayerFriendEventData).DeleteEventDbData(p.M_Player.M_DwUin, 6, Item.AutoId)
								p.M_Player.GetIFGameData("PlayerFriendEventData").(*PlayerFriendEventData).DeleteLocalDataByAutoId(EventAI)

								player, ok := G_GameLogicPtr.M_Players[Item.ReceiveId]
								if ok {
									if player.GetGameData("PlayerCardCollectData") != nil {
										player.GetIFGameData("PlayerCardCollectData").(*PlayerCardCollectData).NOtifyReceiveRefuseExchange(Item)
									}
								} else {
									sqlStr := "SELECT * FROM t_player_card_data WHERE dwUin = ?"
									MsqlStruck := db.SqlCardCollectStruct{}
									units := strings.Split(Item.EventParam, "_")
									cardId, _ := strconv.Atoi(units[1])
									err := db.SqlDb.Get(&MsqlStruck, sqlStr, Item.ReceiveId)
									if err != nil {

									} else {
										if MsqlStruck.CardInfo != "" {
											units := strings.Split(MsqlStruck.CardInfo, ";")

											for i := 0; i < len(units); i++ {
												items := strings.Split(units[i], ",")
												k, _ := strconv.Atoi(items[0])
												cnt, _ := strconv.Atoi(items[1])
												if k == int(cardId) {
													cnt = cnt + 1
													units[i] = items[0] + "," + strconv.Itoa(cnt)
													break
												}
											}
											MsqlStruck.CardInfo = strings.Join(units, ";")
										}
										db.FormatAllMemUpdateDb(&MsqlStruck, "t_player_card_data", "dwUin")
									}

								}
								p.NOtifyRefuseExchange(Item)

								continue
							}
						} else {
							DeleteIds = append(DeleteIds, Item.AutoId)
							EventAI := p.M_Player.GetIFGameData("PlayerFriendEventData").(*PlayerFriendEventData).DeleteEventDbData(p.M_Player.M_DwUin, 6, Item.AutoId)
							p.M_Player.GetIFGameData("PlayerFriendEventData").(*PlayerFriendEventData).DeleteLocalDataByAutoId(EventAI)

							player, ok := G_GameLogicPtr.M_Players[Item.ReceiveId]
							if ok {
								if player.GetGameData("PlayerCardCollectData") != nil {
									player.GetIFGameData("PlayerCardCollectData").(*PlayerCardCollectData).NOtifyReceiveRefuseExchange(Item)
								}
							} else {
								sqlStr := "SELECT * FROM t_player_card_data WHERE dwUin = ?"
								MsqlStruck := db.SqlCardCollectStruct{}
								units := strings.Split(Item.EventParam, "_")
								cardId, _ := strconv.Atoi(units[1])
								err := db.SqlDb.Get(&MsqlStruck, sqlStr, Item.ReceiveId)
								if err != nil {

								} else {
									if MsqlStruck.CardInfo != "" {
										units := strings.Split(MsqlStruck.CardInfo, ";")

										for i := 0; i < len(units); i++ {
											items := strings.Split(units[i], ",")
											k, _ := strconv.Atoi(items[0])
											cnt, _ := strconv.Atoi(items[1])
											if k == int(cardId) {
												cnt = cnt + 1
												units[i] = items[0] + "," + strconv.Itoa(cnt)
												break
											}
										}
										MsqlStruck.CardInfo = strings.Join(units, ";")
									}
									db.FormatAllMemUpdateDb(&MsqlStruck, "t_player_card_data", "dwUin")
								}

							}
							p.NOtifyRefuseExchange(Item)

							continue
						}
					}

				}
			}

		}
		temp = append(temp, Item)
	}
	p.MExchangeData.ExchangeCardItems = temp
	p.DeleteOutlineCardExchange(DeleteIds, "t_Player_ExchangeCard_Box_Data")
}

func (p *PlayerCardCollectData) NotifyDeleteGoldCardSwap() {
	notify := &msg.NotifyDeleteGoldCardSwap{}
	notify.MExchangeCardItems = []*msg.ExchangeCardItem{}
	DeleteIds := []int32{}
	temp := []*msg.ExchangeCardItem{}
	for i := 0; i < len(p.MExchangeData.ExchangeCardItems); i++ {
		if p.MExchangeData.ExchangeCardItems[i].EventType == 2 {
			if p.MExchangeData.ExchangeCardItems[i].SenderId == p.M_Player.M_DwUin {
				if p.MExchangeData.ExchangeCardItems[i].ApplicateStatus == 1 {
					DeleteIds = append(DeleteIds, p.MExchangeData.ExchangeCardItems[i].AutoId)
					EventAI := p.M_Player.GetIFGameData("PlayerFriendEventData").(*PlayerFriendEventData).DeleteEventDbData(p.MExchangeData.ExchangeCardItems[i].ReceiveId, 8, p.MExchangeData.ExchangeCardItems[i].AutoId)
					p.M_Player.GetIFGameData("PlayerFriendEventData").(*PlayerFriendEventData).DeleteLocalDataByAutoId(EventAI)
					p.NOtifyRefuseExchange(p.MExchangeData.ExchangeCardItems[i])
					notify.MExchangeCardItems = append(notify.MExchangeCardItems, p.MExchangeData.ExchangeCardItems[i])
					continue
				}
				if p.MExchangeData.ExchangeCardItems[i].ApplicateStatus == 2 {
					DeleteIds = append(DeleteIds, p.MExchangeData.ExchangeCardItems[i].AutoId)
					EventAI := p.M_Player.GetIFGameData("PlayerFriendEventData").(*PlayerFriendEventData).DeleteEventDbData(p.M_Player.M_DwUin, 6, p.MExchangeData.ExchangeCardItems[i].AutoId)
					p.M_Player.GetIFGameData("PlayerFriendEventData").(*PlayerFriendEventData).DeleteLocalDataByAutoId(EventAI)

					player, ok := G_GameLogicPtr.M_Players[p.MExchangeData.ExchangeCardItems[i].ReceiveId]
					if ok {
						if player.GetGameData("PlayerCardCollectData") != nil {
							player.GetIFGameData("PlayerCardCollectData").(*PlayerCardCollectData).NOtifyReceiveRefuseExchange(p.MExchangeData.ExchangeCardItems[i])
						}
					} else {
						sqlStr := "SELECT * FROM t_player_card_data WHERE dwUin = ?"
						MsqlStruck := db.SqlCardCollectStruct{}
						units := strings.Split(p.MExchangeData.ExchangeCardItems[i].EventParam, "_")
						cardId, _ := strconv.Atoi(units[1])
						err := db.SqlDb.Get(&MsqlStruck, sqlStr, p.MExchangeData.ExchangeCardItems[i].ReceiveId)
						if err != nil {

						} else {
							if MsqlStruck.CardInfo != "" {
								units := strings.Split(MsqlStruck.CardInfo, ";")

								for i := 0; i < len(units); i++ {
									items := strings.Split(units[i], ",")
									k, _ := strconv.Atoi(items[0])
									cnt, _ := strconv.Atoi(items[1])
									if k == int(cardId) {
										cnt = cnt + 1
										units[i] = items[0] + "," + strconv.Itoa(cnt)
										break
									}
								}
								MsqlStruck.CardInfo = strings.Join(units, ";")
							}
							db.FormatAllMemUpdateDb(&MsqlStruck, "t_player_card_data", "dwUin")
						}

					}
					p.NOtifyRefuseExchange(p.MExchangeData.ExchangeCardItems[i])
					notify.MExchangeCardItems = append(notify.MExchangeCardItems, p.MExchangeData.ExchangeCardItems[i])
					continue
				}
			}

		}
		temp = append(temp, p.MExchangeData.ExchangeCardItems[i])
	}
	p.MExchangeData.ExchangeCardItems = temp
	p.DeleteOutlineCardExchange(DeleteIds, "t_Player_ExchangeCard_Box_Data")

	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(notify)
	G_getGameLogic().PackResInfo(agent, "NotifyDeleteGoldCardSwap", data)

}

func (p *PlayerCardCollectData) ReqCompleteExchangeCard(buf []byte) {
	req := &msg.ReqCompleteExchangeCard{}
	proto.Unmarshal(buf, req)
	res := &msg.ResCompleteExchangeCard{}
	ExchangeItem := p.GetExchangeCardItem(req.MExchangeCardItem.AutoId)
	st := &p.MsqlStruck[0]
	if ExchangeItem != nil {
		units := strings.Split(req.MExchangeCardItem.EventParam, "_")
		excardId, _ := strconv.Atoi(units[1])
		cardId, _ := strconv.Atoi(units[0])

		if ExchangeItem.StartTime+3600*24 <= int32(time.Now().Unix()) {
			res.ResultCode = MergeConst.Protocol_Active_CardTime_Outline
			res.MExchangeCardItem = req.MExchangeCardItem
			p.DeleteExchangeCardItem(req.MExchangeCardItem.AutoId)
		} else {
			if p.IsGoldCard(cardId) { //是黄金卡
				if p.M_Player.GetIFGameData("PlayerCardSwapData") != nil {
					isGold := p.M_Player.GetIFGameData("PlayerCardSwapData").(*PlayerCardSwapData).IsLimitCardSwapCard(cardId)
					if isGold { //当期限时活动的黄金卡
						Cnt := p.M_Player.GetIFGameData("PlayerCardSwapData").(*PlayerCardSwapData).GetLimitCardCnt()
						if Cnt >= 2 { //超过交换上线
							res.ResultCode = MergeConst.Protocol_Active_GoldCardTime_Cnt_NoEnouch
							res.MExchangeCardItem = req.MExchangeCardItem
							agent := p.GetPlayer().GetAgentByPlayer()
							data, _ := proto.Marshal(res)
							G_getGameLogic().PackResInfo(agent, "ResCompleteExchangeCard", data)
							return
						} else {
							p.M_Player.GetIFGameData("PlayerCardSwapData").(*PlayerCardSwapData).AddGoldCardExchange()
							NewCnt := p.M_Player.GetIFGameData("PlayerCardSwapData").(*PlayerCardSwapData).GetLimitCardCnt()
							ExchangeItem.ApplicateStatus = 3
							if NewCnt >= 2 { //达到交换上限清理其他未完成黄金卡交易
								p.NotifyDeleteGoldCardSwap()
							}
						}
					} else { //过时的黄金卡交换记录直接删除
						res.ResultCode = MergeConst.Protocol_Active_CardTime_Outline
						res.MExchangeCardItem = req.MExchangeCardItem
						p.DeleteExchangeCardItem(req.MExchangeCardItem.AutoId)
						deleteIDs := []int32{}
						deleteIDs = append(deleteIDs, req.MExchangeCardItem.AutoId)
						p.DeleteOutlineCardExchange(deleteIDs, "t_Player_ExchangeCard_Box_Data")
						agent := p.GetPlayer().GetAgentByPlayer()
						data, _ := proto.Marshal(res)
						G_getGameLogic().PackResInfo(agent, "ResCompleteExchangeCard", data)
						return
					}
				}
			}

			res.MExchangeCardItem = &msg.ExchangeCardItem{}
			dbsql := db.SqlExchangeCardStruct{}
			dbsql.ConfigActId = int32(p.GetCardRecord().Id)
			dbsql.SenderId = req.MExchangeCardItem.SenderId
			dbsql.ReceiveId = req.MExchangeCardItem.ReceiveId
			dbsql.GroupId = req.MExchangeCardItem.GroupId
			dbsql.ApplicateStatus = 3
			dbsql.StartTime = req.MExchangeCardItem.StartTime
			dbsql.EventType = 2
			dbsql.EventParam = req.MExchangeCardItem.EventParam
			dbsql.AutoId = req.MExchangeCardItem.AutoId

			ExchangeItem.ApplicateStatus = 3
			err := db.FormatAllMemUpdateDb(&dbsql, "t_Player_ExchangeCard_Box_Data", "auto_id")
			res.MExchangeCardItem.SenderId = dbsql.SenderId
			res.MExchangeCardItem.ReceiveId = dbsql.ReceiveId
			res.MExchangeCardItem.GroupId = dbsql.GroupId
			res.MExchangeCardItem.ApplicateStatus = dbsql.ApplicateStatus
			res.MExchangeCardItem.StartTime = dbsql.StartTime
			res.MExchangeCardItem.EventType = dbsql.EventType
			res.MExchangeCardItem.EventParam = dbsql.EventParam
			res.MExchangeCardItem.ConfigActId = dbsql.ConfigActId
			res.MExchangeCardItem.AutoId = dbsql.AutoId

			if err == nil {
				p.AddCard(st, int32(excardId), 1, false)
				p.SaveDataFromDB("")

				EventAI := p.M_Player.GetIFGameData("PlayerFriendEventData").(*PlayerFriendEventData).DeleteEventDbData(p.M_Player.M_DwUin, 6, req.MExchangeCardItem.AutoId)
				p.M_Player.GetIFGameData("PlayerFriendEventData").(*PlayerFriendEventData).DeleteLocalDataByAutoId(EventAI)

				EventAuid, sqlst, friendInfo := p.M_Player.GetIFGameData("PlayerFriendEventData").(*PlayerFriendEventData).NewFriendEventToDb(10, p.M_Player.M_DwUin, dbsql.ReceiveId, []interface{}{req.MExchangeCardItem.AutoId, int32(cardId), int32(excardId)})
				p.M_Player.GetIFGameData("PlayerFriendEventData").(*PlayerFriendEventData).NotifyNewFriendEvent(EventAuid, sqlst, friendInfo)

				EventAuid1, sqlst1, friendInfo1 := p.M_Player.GetIFGameData("PlayerFriendEventData").(*PlayerFriendEventData).NewFriendEventToDb(11, dbsql.ReceiveId, p.M_Player.M_DwUin, []interface{}{req.MExchangeCardItem.AutoId, int32(excardId), int32(cardId)})

				player, ok := G_GameLogicPtr.M_Players[dbsql.ReceiveId]
				if ok {
					if player.GetGameData("PlayerCardCollectData") != nil {
						player.GetIFGameData("PlayerCardCollectData").(*PlayerCardCollectData).NotifyCompleteExchangeCard(res.MExchangeCardItem)
					}
					if player.GetGameData("PlayerFriendEventData") != nil {
						player.GetIFGameData("PlayerFriendEventData").(*PlayerFriendEventData).NotifyNewFriendEvent(EventAuid1, sqlst1, friendInfo1)
					}
				}
			}

		}
	} else {
		res.ResultCode = MergeConst.Protocol_Active_CardTime_Outline
		res.MExchangeCardItem = req.MExchangeCardItem
	}

	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(res)
	G_getGameLogic().PackResInfo(agent, "ResCompleteExchangeCard", data)
}

func (p *PlayerCardCollectData) ReqGetExchangeCard(buf []byte) {
	req := &msg.ReqGetExchangeCard{}
	proto.Unmarshal(buf, req)
	res := &msg.ResGetExchangeCard{}
	ExchangeItem := p.GetExchangeCardItem(req.MExchangeCardItem.AutoId)
	st := &p.MsqlStruck[0]
	if ExchangeItem != nil {

		units := strings.Split(req.MExchangeCardItem.EventParam, "_")
		excardId, _ := strconv.Atoi(units[0])

		res.MExchangeCardItem = &msg.ExchangeCardItem{}
		dbsql := db.SqlExchangeCardStruct{}
		dbsql.ConfigActId = int32(p.GetCardRecord().Id)
		dbsql.SenderId = req.MExchangeCardItem.SenderId
		dbsql.ReceiveId = req.MExchangeCardItem.ReceiveId
		dbsql.GroupId = req.MExchangeCardItem.GroupId
		dbsql.ApplicateStatus = 4
		dbsql.StartTime = req.MExchangeCardItem.StartTime
		dbsql.EventType = 2
		dbsql.EventParam = req.MExchangeCardItem.EventParam
		dbsql.AutoId = req.MExchangeCardItem.AutoId
		ExchangeItem.ApplicateStatus = 4

		err := db.FormatAllMemUpdateDb(&dbsql, "t_Player_ExchangeCard_Box_Data", "auto_id")
		res.MExchangeCardItem.SenderId = dbsql.SenderId
		res.MExchangeCardItem.ReceiveId = dbsql.ReceiveId
		res.MExchangeCardItem.GroupId = dbsql.GroupId
		res.MExchangeCardItem.ApplicateStatus = dbsql.ApplicateStatus
		res.MExchangeCardItem.StartTime = dbsql.StartTime
		res.MExchangeCardItem.EventType = dbsql.EventType
		res.MExchangeCardItem.EventParam = dbsql.EventParam
		res.MExchangeCardItem.ConfigActId = dbsql.ConfigActId
		res.MExchangeCardItem.AutoId = dbsql.AutoId

		if err == nil {
			p.AddCard(st, int32(excardId), 1, false)
			p.SaveDataFromDB("")

			EventAI := p.M_Player.GetIFGameData("PlayerFriendEventData").(*PlayerFriendEventData).DeleteEventDbData(p.M_Player.M_DwUin, 11, req.MExchangeCardItem.AutoId)
			p.M_Player.GetIFGameData("PlayerFriendEventData").(*PlayerFriendEventData).DeleteLocalDataByAutoId(EventAI)

			player, ok := G_GameLogicPtr.M_Players[dbsql.SenderId]
			if ok {
				if player.GetGameData("PlayerCardCollectData") != nil {
					player.GetIFGameData("PlayerCardCollectData").(*PlayerCardCollectData).NotifyGetExchangeCard(res.MExchangeCardItem)
				}
			}
		}

	} else {
		res.ResultCode = MergeConst.Protocol_Active_CardTime_Outline
		res.MExchangeCardItem = req.MExchangeCardItem
	}

	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(res)
	G_getGameLogic().PackResInfo(agent, "ResGetExchangeCard", data)
}

func (p *PlayerCardCollectData) CloseNewLimitActivity(args []interface{}) {
	record := args[0].(*gamedata.ActivityRecord)

	if record.Type != p.MActType {
		return
	}

	notify := &msg.NotifyLimitedTimeActiveEnd{}
	notify.DwUin = p.M_Player.M_DwUin
	notify.MActiveList = []*msg.LimitedTimeEndStruct{}

	for i := 0; i < len(p.MsqlStruck); i++ {
		item := p.MsqlStruck[i]
		if int(item.ConfigActId) == record.Id {
			msg := &msg.LimitedTimeEndStruct{}
			msg.ActiveID = item.ActiveID
			msg.Type = int32(record.Type)
			notify.MActiveList = append(notify.MActiveList, msg)
		}
	}
	p.MisDirty = true
	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(notify)
	G_getGameLogic().PackResInfo(agent, "NotifyLimitedTimeActiveEnd", data)
}

func (p *PlayerCardCollectData) Reconnect(b bool) {
	GoUtil.RemoveEvent(MergeConst.CloseNewLimitActivity, p.CloseNewLimitActivity, p)
	GoUtil.RegisterEvent(MergeConst.CloseNewLimitActivity, p.CloseNewLimitActivity, p)
	GoUtil.RemoveEvent(MergeConst.Notify_Daily_Renew, p.NotifyDailyRenew, p)
	GoUtil.RegisterEvent(MergeConst.Notify_Daily_Renew, p.NotifyDailyRenew, p)
	p.PlayerActiveData.Reconnect(b)
	if b {
		p.LoadDataFromDB(p.M_Player.M_DwUin)
	}
}
func (p *PlayerCardCollectData) NotifyDailyRenew(args []interface{}) {
	timeStamp := (int64)(time.Now().Unix())
	t := time.Unix(timeStamp, 0).Local()
	zero := timeStamp - (int64)(t.Hour()*3600+t.Minute()*60+t.Second())
	for i := 0; i < len(p.MsqlStruck); i++ {

		if p.MsqlStruck[i].RenewSvrTime < int32(zero) {
			p.MsqlStruck[i].RenewSvrTime = int32(zero)
			p.MsqlStruck[i].RenewExchangeTime = 0
			p.MsqlStruck[i].RenewRequestTime = 0
			p.NotifyCardDailyRenew(&p.MsqlStruck[i])
		}
	}
}

func (p *PlayerCardCollectData) FindDbSt(activeId int32) *db.SqlCardCollectStruct {
	for i := 0; i < len(p.MsqlStruck); i++ {
		if p.MsqlStruck[i].ActiveID == activeId {
			return &p.MsqlStruck[i]
		}
	}
	return nil
}

func (p *PlayerCardCollectData) ResCardCollectDetail(buf []byte) {
	req := &msg.ReqCardCollectDetail{}
	proto.Unmarshal(buf, req)
	st := p.FindDbSt(req.ActiveID)
	res := &msg.ResCardCollectDetail{}
	if st != nil {

		res.ActiveID = st.ActiveID
		res.CardInfo = st.CardInfo
		res.Fragment = st.Fragment
		res.FinalReward = st.FinalReward
		res.CardRewardInfo = st.CardRewardInfo
		res.MasterCards = st.MasterCards
		res.CurSvrTime = int32(time.Now().Unix())
		res.StartSvrTime = st.StartSvrTime
		res.EndSvrTime = st.EndSvrTime
		res.DwUin = p.M_Player.M_DwUin
		res.Universal = st.Universal
		res.RenewSvrTime = st.RenewSvrTime
		res.RenewExchangeTime = st.RenewExchangeTime
		res.RenewRequestTime = st.RenewRequestTime
		res.ResultCode = 0

	} else {
		res.ResultCode = MergeConst.Protocol_Active_No_Exsit
	}
	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(res)
	G_getGameLogic().PackResInfo(agent, "ResCardCollectDetail", data)
}

func (p *PlayerCardCollectData) NotifyCardDailyRenew(st *db.SqlCardCollectStruct) {

	notify := &msg.NotifyCardDailyRenew{}
	notify.ActiveID = st.ActiveID
	notify.RenewExchangeTime = st.RenewExchangeTime
	notify.RenewRequestTime = st.RenewRequestTime

	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(notify)
	G_getGameLogic().PackResInfo(agent, "NotifyCardDailyRenew", data)
	p.SaveDataFromDB("")
}

func (p *PlayerCardCollectData) GetIsGetRewardById(st *db.SqlCardCollectStruct, id int32) bool {
	if st.CardRewardInfo == "" {
		return false
	} else {
		units := strings.Split(st.CardRewardInfo, ",")
		for i := 0; i < len(units); i++ {
			cnt, _ := strconv.Atoi(units[i])
			if int32(cnt) == id {
				return true
			}
		}
	}
	return false
}

func (p *PlayerCardCollectData) GetAlbumRewardById(st *db.SqlCardCollectStruct, id int32) {
	if st.CardRewardInfo == "" {
		st.CardRewardInfo = strconv.Itoa(int(id))
	} else {
		st.CardRewardInfo = st.CardRewardInfo + "," + strconv.Itoa(int(id))
	}
}

func (p *PlayerCardCollectData) DeleteOneCard(st *db.SqlCardCollectStruct, id int32) {
	if st.CardInfo != "" {
		units := strings.Split(st.CardInfo, ";")
		isHave := false
		for i := 0; i < len(units); i++ {
			items := strings.Split(units[i], ",")
			k, _ := strconv.Atoi(items[0])
			cnt, _ := strconv.Atoi(items[1])
			if k == int(id) {
				cnt = cnt - 1
				units[i] = items[0] + "," + strconv.Itoa(cnt)
				isHave = true
				break
			}
		}
		if !isHave {

		} else {
			st.CardInfo = strings.Join(units, ";")
		}

	} else {

	}
	return
}

func (p *PlayerCardCollectData) GetCardCnt(st *db.SqlCardCollectStruct, id int32) int {
	Cnt := 0
	if st.CardInfo != "" {
		units := strings.Split(st.CardInfo, ";")
		for i := 0; i < len(units); i++ {
			items := strings.Split(units[i], ",")
			k, _ := strconv.Atoi(items[0])
			cnt, _ := strconv.Atoi(items[1])
			if k == int(id) {
				return cnt
			}
		}
	}
	return Cnt
}

func (p *PlayerCardCollectData) AddCard(st *db.SqlCardCollectStruct, id int32, count int32, isAddFragment bool) int32 {
	AddFragment := 0
	CardDetailCfg := gamedata.GetConfigByName("CardDetailCfg")
	record1 := CardDetailCfg.Index(int(id))
	record := record1.(*gamedata.CardDetailRecord)
	if st.CardInfo != "" {
		units := strings.Split(st.CardInfo, ";")
		isHave := false
		for i := 0; i < len(units); i++ {
			items := strings.Split(units[i], ",")
			k, _ := strconv.Atoi(items[0])
			cnt, _ := strconv.Atoi(items[1])
			if k == int(id) {
				cnt = cnt + int(count)
				units[i] = items[0] + "," + strconv.Itoa(cnt)
				AddFragment = AddFragment + int(count)*int(record.Star)
				isHave = true
				break
			}
		}
		if !isHave {
			st.CardInfo = st.CardInfo + ";" + strconv.Itoa(int(id)) + "," + strconv.Itoa(int(count))
			AddFragment = AddFragment + int(count-1)*int(record.Star)
		} else {
			st.CardInfo = strings.Join(units, ";")
		}

	} else {
		st.CardInfo = strconv.Itoa(int(id)) + "," + strconv.Itoa(int(count))
		AddFragment = AddFragment + int(count-1)*int(record.Star)
	}
	if !isAddFragment {
		AddFragment = 0
	}
	return int32(AddFragment)
}

func (p *PlayerCardCollectData) ReqAddCard(buf []byte) {
	req := &msg.ReqAddCard{}
	proto.Unmarshal(buf, req)
	st := p.FindDbSt(req.ActiveID)
	res := &msg.ResAddCard{}

	if st != nil {
		res.ActiveID = st.ActiveID
		res.Id = req.Id
		res.Count = req.Count
		st.Universal = st.Universal + req.Count
		AddFragment := p.AddCard(st, req.Id, req.Count, true)
		st.Fragment = st.Fragment + AddFragment
		res.Fragment = st.Fragment
	} else {
		res.ResultCode = MergeConst.Protocol_Active_No_Exsit
	}
	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(res)
	G_getGameLogic().PackResInfo(agent, "ResAddCard", data)
	p.SaveDataFromDB("")
}

func (p *PlayerCardCollectData) ResUnpackCard(buf []byte) {
	req := &msg.ReqUnpackCard{}
	proto.Unmarshal(buf, req)
	st := p.FindDbSt(req.ActiveID)
	res := &msg.ResUnpackCard{}

	if st != nil {
		res.ActiveID = st.ActiveID
		res.CardIds = req.CardIds
		res.CardCnts = req.CardCnts
		res.PackID = req.PackID
		var AddFragment int32 = 0
		for i := 0; i < len(req.CardIds); i++ {
			add := p.AddCard(st, req.CardIds[i], req.CardCnts[i], true)
			AddFragment = AddFragment + add
			st.Universal = st.Universal + req.CardCnts[i]
		}
		st.Fragment = st.Fragment + AddFragment
		res.Fragment = st.Fragment
	} else {
		res.ResultCode = MergeConst.Protocol_Active_No_Exsit
	}
	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(res)
	G_getGameLogic().PackResInfo(agent, "ResUnpackCard", data)
	p.SaveDataFromDB("")
}

func (p *PlayerCardCollectData) ReqUpdateStickerCount(buf []byte) {
	req := &msg.ReqUpdateStickerCount{}
	res := &msg.ResUpdateStickerCount{}
	proto.Unmarshal(buf, req)
	st := p.FindDbSt(req.ActiveID)

	if st != nil {
		st.Fragment += req.Sticker
	} else {
		res.ResultCode = MergeConst.Protocol_Active_No_Exsit
	}
	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(res)
	G_getGameLogic().PackResInfo(agent, "ResUpdateStickerCount", data)
	p.SaveDataFromDB("")
}

func (p *PlayerCardCollectData) AddMasterCard(st *db.SqlCardCollectStruct, id int32, count int32) {
	if st.MasterCards != "" {
		units := strings.Split(st.MasterCards, ";")
		isHave := false
		for i := 0; i < len(units); i++ {
			items := strings.Split(units[i], ",")
			k, _ := strconv.Atoi(items[0])
			cnt, _ := strconv.Atoi(items[1])
			if k == int(id) {
				cnt = cnt + int(count)
				units[i] = items[0] + "," + strconv.Itoa(cnt)
				isHave = true
				break
			}
		}
		if !isHave {
			st.MasterCards = st.MasterCards + ";" + strconv.Itoa(int(id)) + "," + strconv.Itoa(int(count))
		} else {
			st.MasterCards = strings.Join(units, ";")
		}

	} else {
		st.MasterCards = strconv.Itoa(int(id)) + "," + strconv.Itoa(int(count))
	}
}

func (p *PlayerCardCollectData) ReqAddMasterCard(buf []byte) {
	req := &msg.ReqAddMasterCard{}
	proto.Unmarshal(buf, req)
	st := p.FindDbSt(req.ActiveID)
	res := &msg.ResAddMasterCard{}

	if st != nil {
		res.ActiveID = st.ActiveID
		res.Id = req.Id
		res.Count = req.Count
		p.AddMasterCard(st, req.Id, req.Count)
	} else {
		res.ResultCode = MergeConst.Protocol_Active_No_Exsit
	}
	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(res)
	G_getGameLogic().PackResInfo(agent, "ResAddMasterCard", data)
	p.SaveDataFromDB("")
}

func (p *PlayerCardCollectData) UseMasterCard(st *db.SqlCardCollectStruct, id int32, count int32) bool {
	if st.MasterCards != "" {
		units := strings.Split(st.MasterCards, ";")
		isHave := false
		for i := 0; i < len(units); i++ {
			items := strings.Split(units[i], ",")
			k, _ := strconv.Atoi(items[0])
			cnt, _ := strconv.Atoi(items[1])
			if k == int(id) && cnt >= int(count) {
				cnt = cnt - int(count)
				units[i] = items[0] + "," + strconv.Itoa(cnt)
				isHave = true
				break
			}
		}
		if !isHave {
			// st.MasterCards = st.MasterCards + ";" + strconv.Itoa(int(id)) + "," + strconv.Itoa(int(count))
		} else {
			st.MasterCards = strings.Join(units, ";")
			return true
		}

	} else {
		// st.MasterCards = strconv.Itoa(int(id)) + "," + strconv.Itoa(int(count))
	}
	return false
}

func (p *PlayerCardCollectData) ReqBuyStickerItem(buf []byte) {
	req := &msg.ReqBuyStickerItem{}
	proto.Unmarshal(buf, req)
	st := p.FindDbSt(req.ActiveID)
	res := &msg.ResBuyStickerItem{}

	if st != nil {
		res.ActiveID = st.ActiveID

		if st.Fragment >= req.CostSticker {
			st.Fragment = st.Fragment - req.CostSticker
			res.Id = req.Id
			res.CurFragment = st.Fragment
			res.ResultCode = 0
		} else {
			res.ResultCode = MergeConst.Protocol_Active_CardFragment_NoEnough
		}

	} else {
		res.ResultCode = MergeConst.Protocol_Active_No_Exsit
	}
	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(res)
	G_getGameLogic().PackResInfo(agent, "ResBuyStickerItem", data)
	p.SaveDataFromDB("")
}

func (p *PlayerCardCollectData) ReqUseMasterCard(buf []byte) {
	req := &msg.ReqUseMasterCard{}
	proto.Unmarshal(buf, req)
	st := p.FindDbSt(req.ActiveID)
	res := &msg.ResUseMasterCard{}

	if st != nil {
		res.ActiveID = st.ActiveID

		res.MasterId = req.MasterId
		res.ExchangeCardId = req.ExchangeCardId
		isUse := p.UseMasterCard(st, req.MasterId, 1)
		if isUse {
			AddFrament := p.AddCard(st, req.ExchangeCardId, 1, true)
			st.Fragment = st.Fragment + AddFrament
			res.Fragment = st.Fragment
			res.ResultCode = 0
		} else {
			res.ResultCode = MergeConst.Protocol_Active_Card_NoEnough
		}

	} else {
		res.ResultCode = MergeConst.Protocol_Active_No_Exsit
	}
	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(res)
	G_getGameLogic().PackResInfo(agent, "ResUseMasterCard", data)
	p.SaveDataFromDB("")
}
func (p *PlayerCardCollectData) ResGetCardAlbumReward(buf []byte) {
	req := &msg.ReqGetCardAlbumReward{}
	proto.Unmarshal(buf, req)
	st := p.FindDbSt(req.ActiveID)
	res := &msg.ResGetCardAlbumReward{}
	if st != nil {
		res.ActiveID = st.ActiveID
		res.Id = req.Id
		if p.GetIsGetRewardById(st, req.Id) {
			res.ResultCode = MergeConst.Protocol_Active_Card_Rewarded
		} else {
			res.ResultCode = 0
			p.GetAlbumRewardById(st, req.Id)
			p.SaveDataFromDB("")
		}
	} else {
		res.ResultCode = MergeConst.Protocol_Active_No_Exsit
	}
	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(res)
	G_getGameLogic().PackResInfo(agent, "ResGetCardAlbumReward", data)
}

func (p *PlayerCardCollectData) ResGetAllCardReward(buf []byte) {
	req := &msg.ReqGetAllCardReward{}
	proto.Unmarshal(buf, req)
	st := p.FindDbSt(req.ActiveID)
	res := &msg.ResGetAllCardReward{}
	if st != nil {
		if st.FinalReward == int32(1) {
			res.ResultCode = MergeConst.Protocol_Active_Card_Rewarded
		} else {
			res.ResultCode = 0
			st.FinalReward = 1
			p.SaveDataFromDB("")
		}
	} else {
		res.ResultCode = MergeConst.Protocol_Active_No_Exsit
	}
	agent := p.GetPlayer().GetAgentByPlayer()
	data, _ := proto.Marshal(res)
	G_getGameLogic().PackResInfo(agent, "ResGetAllCardReward", data)
}

func (p *PlayerCardCollectData) SaveDataFromDB(Key interface{}) bool {
	for i := 0; i < len(p.MsqlStruck); i++ {
		item := p.MsqlStruck[i]
		db.FormatAllMemUpdateDb(&item, "t_player_card_data", "ActiveID")
	}
	return true
}
func (p *PlayerCardCollectData) ClearData() bool {
	p.SaveDataFromDB("")
	GoUtil.RemoveEvent(MergeConst.CloseNewLimitActivity, p.CloseNewLimitActivity, p)
	GoUtil.RemoveEvent(MergeConst.Notify_Daily_Renew, p.NotifyDailyRenew, p)
	p.PlayerActiveData.ClearData()

	return true
}
